-1

I have array list with value like

x-tag
125
154
166
125
125
222
125

In above list,it has value 125 for 4 time I have the value 125 from another and i can check whether list having 125 or not. But not able to find how many times it occur or present in list

4

4 Answers 4

11

Use Collections#frequency() method:

List<Integer> list = Arrays.asList(125, 154, 166, 125, 125, 222, 125);
int totalCount = Collections.frequency(list, 125);
0
2

You can use Guava libraries Multiset, elements of a Multiset that are equal to one another are referred to as occurrences of the same single element.

Multiset<Integer> myMultiset = HashMultiset.create();
myMultiset.addAll(list);
System.out.println(myMultiset.count(125)); // 4
1
List<Integer> list = Arrays.asList(125,154,166,125,125,222,125);

int count = Collections.frequency(list, 125);

System.out.println("total count: " + tcount);

Output:

total count: 4   
0
1

Also possible to map it into a map. Bit more code though:

package com.stackoverflow.counter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Count {
    public Map<Integer,Integer> convertToMap(List<Integer> integerList) {
        Map<Integer,Integer> integerMap = new HashMap<>();
        for (Integer i: integerList) {
            Integer numberOfOccurrences = integerMap.get(i);
            if (numberOfOccurrences == null)
                numberOfOccurrences = 0;
            integerMap.put(i,++numberOfOccurrences);
        }
        return integerMap;
    }
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(3);
        integerList.add(2);
        integerList.add(1);
        integerList.add(3);
        integerList.add(2);
        integerList.add(4);
        integerList.add(5);
        integerList.add(5);
        Count count = new Count();
        Map<Integer, Integer> integerMap = count.convertToMap(integerList);
        for (Integer i: integerMap.keySet()) {
            System.out.println("Number: " + i + ", found " + integerMap.get(i) + " times.");
        }
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.