Count the numbers and its repetition counts in list using Java
We can solve this problem in many ways , but one of the easiest way to convert it is. Time taken to complete it 5 mins
we can loop the given list of numbers and can push data to Map and maintain
number and its count
Below is the snippet where we are going to solve the problem
below is the answer :
package collections;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> list=Arrays.asList(2,3,2,3,4,1,5,1);
Map<Integer,Integer> mapCount= new HashMap<>();
int count=0;
Map<Object, Long> counts=list.stream().collect(Collectors.groupingBy(e->e,Collectors.counting()));
for(Map.Entry e:counts.entrySet()) {
System.out.println(e.getKey() + “: “+ e.getValue());
}
}
}