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.
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.
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? 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.
List asList = Arrays.asList(array); Set<String> mySet = new HashSet<String>(asList); for(String s: mySet){ System.out.println(s + " " + Collections.frequency(asList,s)); }
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:
Stream<String>
from the original arrayMap<String, List<String>>
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! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With