osimer pothe
osimer pothe

Reputation: 2897

Count occurence of string in Arraylist

Let us assume I have the following list .

List<String> list=new ArrayList<String>();
list.add("sultan");
list.add("Masum");
list.add("sultan");
list.add("Sorry");
list.add("sultan");
list.add("Masum");
list.add("sultan");
list.add("Tarek");
list.add("sultan");

I want to know the count of occurrence of each string in Arraylist . How can I do that ? And I also want to know the string that is occurred in this Arraylist at highest times. For this particular example, the answer is "Sultan" .

Upvotes: 0

Views: 572

Answers (3)

Olimpiu POP
Olimpiu POP

Reputation: 5067

If you want all the strings in the first list something you could do is:

import java.util.*;

import java.util.Map.Entry;
//...

Set<String> uniques = new HashSet(list);
Map<String, Integer> counts = new HashMap<String, Integer>();

for (String elem : uniques) {
    counts.put(elem, Collections.frequency(list, elem));
}

So in the end you will have the count for each string in the map. Putting one to one...this would do the following:

  • by creating the set from the initial list you will have each string from your list, afterwards you "walk" your list and compute for each the frequency for any given string.

As for the highest frequency, you could use the Collections.max method on the entry set like this:

Collections.max(counts.entrySet(), new Comparator<Entry<String, Integer>>() {
        @Override
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            return (o1.getValue() - o2.getValue());
        }
    })

Upvotes: 2

Manish Kumar
Manish Kumar

Reputation: 10482

Check this

Collections.frequency and THIS EXAMPLE

from this example:

System.out.println("\nExample 1 - Count 'a' with frequency");
System.out.println("a : " + Collections.frequency(list, "a"));

System.out.println("\nExample 2 - Count all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
    System.out.println(temp + ": " + Collections.frequency(list, temp));
}

System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();

for (String temp : list) {
    Integer count = map.get(temp);
    map.put(temp, (count == null) ? 1 : count + 1);
}
printMap(map);

System.out.println("\nSorted Map");
Map<String, Integer> treeMap = new TreeMap<String, Integer>(map);
printMap(treeMap);

Upvotes: 1

wawek
wawek

Reputation: 1597

It may be helpful

int occ = Collections.frequency(list, "Masum");

Upvotes: 3

Related Questions