Home > Net >  How to convert data from the List of strings into a Map<String, Integer> with Stream API?
How to convert data from the List of strings into a Map<String, Integer> with Stream API?

Time:04-01

I tried to convert data from the list of strings into a Map<String, Integer> with the Stream API.

But the way I did it is not correct:

public static Map<String, Integer> converter (List<String> data){
        return data.stream().collect(Collectors.toMap(e->e, Function.identity()));

If we have List.of("5", "7", "5", "8", "9", "8")

task №1 as key - String, and value - character frequency

task №2 as key - String, and value - string converted to integer

CodePudding user response:

Try it like this for a frequency. Note the a map can't have duplicate keys.

List<String> list2 = List.of("5", "7", "5", "8", "9","8");
  • the key is the String.
  • the value starts a 1.
  • the Integers::sum adds 1 for every occurrence.
Map<String, Integer> freq = list2.stream().collect(Collectors.toMap(
         e->e, (a)->1, Integer::sum));

freq.entrySet().forEach(System.out::println);

prints

5=2
7=1
8=2
9=1
  • Related