Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rank ArrayList<String> with int in java

I want to rank in java an ArrayList<String> with the number of times that the String appears. Like this: if I have an

ArrayList<String>= [French, English, German, French, French, Belgium, English, Belgium]

I count the number that "French", "English", "Belgium",etc. appear. So French appear 3 times, English 2 times, Belgium 2 times, German one times. Then I want to rank the ArrayList<String> in function of the number.

The result will be:

French 3
English 2 
Belgium 2
German 1

How I can do this? How to associate an integer and a String?

like image 823
user51324 Avatar asked Feb 12 '23 18:02

user51324


1 Answers

Don't reinvent the wheel and use the frequency method of the Collections class:

public static int frequency(Collection<?> c, Object o)

Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).

If you need to count the occurrences for all elements, use a Map and loop cleverly :) Or put your list in a Set and loop on each element of the set with the frequency method above. HTH

EDIT / Java 8: If you fancy a more functional, Java 8 one-liner solution with lambdas, try:

Map<String, Long> occurrences = 
  list.stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));

And then sort the map by value.

like image 79
VH-NZZ Avatar answered Feb 15 '23 08:02

VH-NZZ