Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java count occurrence of each item in an array

Tags:

java

arrays

count

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.

like image 918
Favolas Avatar asked Nov 11 '11 18:11

Favolas


People also ask

How do you count occurrences of each element in an array?

The frequency of an element can be counted using two loops. One loop will be used to select an element from an array, and another loop will be used to compare the selected element with the rest of the array. Initialize count to 1 in the first loop to maintain a count of each element.

How do you check for occurrence in an array?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do you find all occurrences of an element in a list in Java?

How do you find all occurrences of an element in a list in Java? Using IntStream. To find an index of all occurrences of an item in a list, you can create an IntStream of all the indices and apply a filter over it to collect all matching indices with the given value.


2 Answers

List asList = Arrays.asList(array); Set<String> mySet = new HashSet<String>(asList);  for(String s: mySet){  System.out.println(s + " " + Collections.frequency(asList,s)); } 
like image 151
Damian Avatar answered Sep 22 '22 05:09

Damian


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:

  • Stream
  • Collectors

Hope it helps! :)

like image 26
Alexis C. Avatar answered Sep 23 '22 05:09

Alexis C.