0

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

Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
user2354846
  • 41
  • 1
  • 5

4 Answers4

11

Use Collections#frequency() method:

List<Integer> list = Arrays.asList(125, 154, 166, 125, 125, 222, 125);
int totalCount = Collections.frequency(list, 125);
Bohemian
  • 389,931
  • 88
  • 552
  • 692
Rohit Jain
  • 203,151
  • 43
  • 392
  • 509
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
Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101
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   
Maxim Shoustin
  • 78,004
  • 28
  • 199
  • 222
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.");
        }
    }
}
AppX
  • 528
  • 2
  • 12