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 theString
. - the
value
starts a1
. - the
Integers::sum
adds1
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