Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading