Home > Software engineering >  I need to put an array of integers into a map, key is number of digits using stream
I need to put an array of integers into a map, key is number of digits using stream

Time:06-07

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"]

CodePudding user response:

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]}

CodePudding user response:

List<Integer> data = List.of(1,10,200,-22,51,54,40442,
              99291,92293,4022,402,-23, -44, -77, -88102,102,88);

Map<Integer, List<String>> map groupByDigitNumbers(data);

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

prints

1=[o1]
2=[e10, o51, e54, e88]
3=[e200, e402, e102, e102]
4=[e4022]
5=[e40442, o99291, o92293]
  • first stream the numbers
  • then group them by the number of digits using Math.log10(i) 1.
  • then map them to the appropriate String using Collectors.mapping.
public static Map<Integer, List<String>>
        groupByDigitNumbers(List<Integer> list) {
    return list.stream()
            .filter(num -> num >= 0)
            .collect(Collectors.groupingBy(
                    i -> (int) Math.log10(i)   1,
                    Collectors.mapping(
                            i -> i % 2 == 0 ? "e"   i : "o"   i,
                            Collectors.toList())));
    
}
  • Related