Hi so i have an array of integers and i have to put it into a map key is number of digits. I know i should use stream groupingBy but i have a problem.
i have this piece of code:
public static Map<Integer, List<String>> groupByDigitNumbers( List<Integer> x){
return x.stream()
.collect(Collectors.groupingBy(n->Integer.toString(n).length()));
}
but my values should be stored as List of Strings not integers
Also should filter negative values and if the number is even there should be ‘e’ at the beginning of a string if odd ‘o’.
Example [17,2,44,183,4] the output should be
1->["e2","e4"]; 2->["o17","e44"]; 3->["o183"]
>Solution :
Add a filter in the stream for the negative values, and a Collectors.mapping in the groupingBy to modify each value
public static Map<Integer, List<String>> groupByDigitNumbers(List<Integer> x) {
return x.stream()
.filter(n -> n >= 0)
.collect(Collectors.groupingBy(n -> Integer.toString(n).length(),
Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d, Collectors.toList())));
}
List<Integer> values = List.of(-23, 17, 2, 44, 183, 4);
Map<Integer, List<String>> result = groupByDigitNumbers(values);
System.out.println(result);
// {1=[e2, e4], 2=[o17, e44], 3=[o183]}