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
I think you are looking for something like this (I didn't compile it, but it should get you going in the right direction):
You are looking for
Map<String, Integer>
data structure, notSet
Something like
Map is the data structure that maps unique to value
means You want to know how many "M1" contains in List(list), how many "M2", instead of using set interface, you can use the Map interface because Map contain the key, value pair format ,i.e. Map data structure.
Set
won't help you in this case, you need a Map:Much easier way: use
Collections.frequency()
System.out.println("M2: "+Collections.frequency(list,"M2");
will output
M2: 1