How to count the number of occurrences of an element in a List with Java

2 Answers

0 votes
import java.util.Collections;
import java.util.Arrays;
import java.util.List;

public class MyClass {
    public static void main(String args[]) {
        List<String> list = Arrays.asList("java", "c", "c", "c++", "java", "python", "java");
        
        int count = Collections.frequency(list, "java");
        
        System.out.println(count);
    }

}



 
/*
run:
        
3
    
*/

 



answered Oct 10, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        List<String> list = Arrays.asList("java", "c", "c", "c++", "java", "python", "java");
         
        int count = 0;
        for (String s : list) {
            if (s.equals("java")) {
                count++;
            }
        }
         
        System.out.println(count);
    }
 
}
 
 
 
  
/*
run:
         
3
     
*/

 



answered Oct 10, 2023 by avibootz

Related questions

...