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.");
}
}
}