Articles → Java → Count The Duplicate Elements In Arraylist In Java
Count The Duplicate Elements In Arraylist In Java
Code
import java.util. * ;
import java.lang. * ;
import java.io. * ;
/* Name of the class has to be "Main" only if the class is public. */
class MyClass {
public static void main(String[] args) throws java.lang.Exception {
List < String > list = new ArrayList < String > ();
list.add("Test");
list.add("Test1");
list.add("Test");
Set < String > unique = new HashSet < String > (list);
for (String key: unique) {
System.out.println(key + ": " + Collections.frequency(list, key));
}
}
}
Output
Click to Enlarge