Java count occurrence of each item in an array
Solution 1
You could use a MultiSet
from Google Collections/Guava or a Bag
from Apache Commons.
If you have a collection instead of an array, you can use addAll()
to add the entire contents to the above data structure, and then apply the count()
method to each value. A SortedMultiSet
or SortedBag
would give you the items in a defined order.
Google Collections actually has very convenient ways of going from arrays to a SortedMultiset
.
Solution 2
List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet){
System.out.println(s + " " + Collections.frequency(asList,s));
}
Solution 3
With java-8, you can do it like this:
String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k+" "+v.size()));
Output:
name5 1
name4 1
name3 1
name2 2
name1 1
What it does is:
- Create a
Stream<String>
from the original array - Group each element by identity, resulting in a
Map<String, List<String>>
- For each key value pair, print the key and the size of the list
If you want to get a Map
that contains the number of occurences for each word, it can be done doing:
Map<String, Long> map = Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
For more informations:
Hope it helps! :)
Solution 4
I wrote a solution for this to practice myself. It doesn't seem nearly as awesome as the other answers posted, but I'm going to post it anyway, and then learn how to do this using the other methods as well. Enjoy:
public static Integer[] countItems(String[] arr)
{
List<Integer> itemCount = new ArrayList<Integer>();
Integer counter = 0;
String lastItem = arr[0];
for(int i = 0; i < arr.length; i++)
{
if(arr[i].equals(lastItem))
{
counter++;
}
else
{
itemCount.add(counter);
counter = 1;
}
lastItem = arr[i];
}
itemCount.add(counter);
return itemCount.toArray(new Integer[itemCount.size()]);
}
public static void main(String[] args)
{
String[] array = {"name1","name1","name2","name2", "name2", "name3",
"name1","name1","name2","name2", "name2", "name3"};
Arrays.sort(array);
Integer[] cArr = countItems(array);
int num = 0;
for(int i = 0; i < cArr.length; i++)
{
num += cArr[i]-1;
System.out.println(array[num] + ": " + cArr[i].toString());
}
}
Solution 5
Using HashMap it is walk in the park.
main(){
String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
Map<String,Integer> hm = new HashMap();
for(String x:array){
if(!hm.containsKey(x)){
hm.put(x,1);
}else{
hm.put(x, hm.get(x)+1);
}
}
System.out.println(hm);
}
Favolas
Updated on December 29, 2021Comments
-
Favolas over 2 years
Is there any method for counting the occurrence of each item on an array?
Lets say I have:
String[] array = {"name1","name2","name3","name4", "name5"};
Here the output will be:
name1 1 name2 1 name3 1 name4 1 name5 1
and if I have:
String[] array = {"name1","name1","name2","name2", "name2"};
The output would be:
name1 2 name2 3
The output here is just to demonstrate the expected result.
-
james.garriss over 10 yearsThe link to Bag is 404.
-
akshayb almost 10 yearsfrom my experience, Collections.frequency is too slow.Avoid if performance is a concern.
-
Tuan over 9 yearsI used getCardinalityMap() from org.apache.commons.collections.CollectionUtils.
-
jrenk over 8 yearsYou may want to provide some explanation to your code.
-
Jorn Vernee about 8 yearsThis doesn't work, you'd have to use
hash.put(s, hash.get(s) + 1);
. Doingi++;
doesn't update the integer inside the hashtable. There's also other typos. -
Damian almost 8 yearsNot really, if it is a HashSet or HashMap.
-
Gopal00005 over 6 yearsIt won't work for array like this: String[] array = { "Gates", "Michael","Gates","Peterson","Bush","Johnson","Johnson","Gates"};
-
naveenTekkem almost 5 yearsWe can also pass the sampleList above to constructor of TreeSet and then loop to get the result
-
ikel almost 3 yearsthis works, but could explain little about hm.put(x, hm.get(x)+1); part ? thx
-
ikel almost 3 yearsI meant how is hm.get(x) actually act like a counter not item value?
-
Deva44 almost 3 years@ikel If key (x in this case) is already there in the hm, get the corresponding value, increment by one and store it back.