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
  • 209,639
  • 45
  • 409
  • 525
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
  • 412,405
  • 93
  • 575
  • 722
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
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
  • 40,646
  • 13
  • 77
  • 103
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
  • 77,483
  • 27
  • 203
  • 225
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