Tuesday, 6 August 2013

Using Java's built-in Set classes to count EACH(keyword) unique element in List values from a list

Using Java's built-in Set classes to count EACH(keyword) unique element in
List values from a list

Given a list that could contain duplicates (like the one below), I need to
be able to count Each(keyword) number of unique elements.
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
list.add("M1");
list.add("M1");
list.add("M2");
list.add("M3");
set.addAll(list);
System.out.println(set.size());
How do I get the count each unique element from the List? That means i
want to know how many "M1" contains in List(list), how many "M2", etc.
The result should be the following:
2 M1
1 M2
1 M3

No comments:

Post a Comment