Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 grouping function to return Map<String, Integer> instead of Map<String,Long>

I am using the below mentioned code to find number of Times each word as occurred in a String.

Map<String, Long> map = Arrays.asList(text.split("\\s+")).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting()))

this code returns Map<String, Long> I want to transform this code to return Map<String, Integer>. I tried doing this by using the code below,

But It throws ClassCastException java.lang.Integer cannot be cast to java.lang.Long

Map<String, Integer> map1 = 
 map.entrySet().parallelStream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> Integer.valueOf(entry.getValue())));

Please help me solve this, I need it to Return Map

like image 655
Lucie Avatar asked Jul 29 '26 00:07

Lucie


1 Answers

You can perform a conversion of Long to Integer after the counting like

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));

but you may also counting using an int value type in the first place:

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
        Collectors.summingInt(word -> 1)));

This is summing a one for each word. You can use the same approach with the toMap collector:

Map<String, Integer> map = Arrays.stream(text.split("\\s+"))
    .collect(Collectors.toMap(Function.identity(), word -> 1, Integer::sum));
like image 135
Holger Avatar answered Jul 30 '26 19:07

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!