Home > Back-end >  Group by integer count
Group by integer count

Time:10-13

I have a List of Integers and I'm trying to count the frequency of each number using the streams API:

// List looks like [5,6]

Map<String, Long> map = array.stream()
.collect(
    Collectors.groupingBy(Integer::valueOf, Collectors.counting())
);

However, compilation fails with the below:

error: incompatible types: inference variable K has incompatible bounds
                .collect(
                        ^
    equality constraints: String
    lower bounds: Integer

How do I achieve what I want to do?

CodePudding user response:

Your resulting map has a String as key, not an Integer.

Either convert it to a string:

Map<String, Long> map = array.stream()
.collect(
    Collectors.groupingBy(Integer::toString, Collectors.counting())
);

or use an Integer as the key:

Map<Integer, Long> map = array.stream()
.collect(
    Collectors.groupingBy(Function.identity(), Collectors.counting())
);

CodePudding user response:

The problem is your map type: Map<String, Long> mismatch Map<Integer,Long>

Map<String, Long> map = array.stream()
.collect(
    Collectors.groupingBy(Integer::valueOf, Collectors.counting())
);

to

Map<Integer, Long> map = array.stream()
.collect(
    Collectors.groupingBy(Integer::valueOf, Collectors.counting())
);

CodePudding user response:

    public static void main(String[] args) 
{   
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(2);
    list.add(3);
    list.add(4);
    
    Map<Integer, Long> result = list.stream()
              .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    System.out.println(result);
    
    
}

Result is :{1=2, 2=2, 3=1, 4=1}

I think that the problem is with that that Map is declared as <String, Long>

  • Related