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

Convert List<Integer> into Map<Integer, V> using streams

I am new to Java 8, I want to print Square of even number from the list and print the result in key value pair, where Key is the even number from the List and value is square of that number.

public class SquareNumber {
    public static void main(String[] args) {
        List<Integer> number = Arrays.asList(289, 452, 533, 656, 744);

        Map<Integer, Integer> map = number.stream()
            .filter(n -> n%2 == 0)
            .map(n -> n*n)
            .distinct()
            .collect(Collectors.toMap(n -> n,  Integer::intValue));

        System.out.println(map);
    }
}

>Solution :

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

Your .map(n -> n*n) step is transforming all of your values across the board. You only want to apply that to your map’s values:

public class Untitled {
    public static void main(String[] args) {
        List<Integer> number = Arrays.asList(289, 452, 533, 656, 744);

        Map<Integer, Integer> map = number.stream()
            .filter(n -> n%2==0)
         // .map(n -> n*n) // Remove this
            .distinct()
            .collect(Collectors.toMap(n -> n,  n -> n*n)); // Square only your map's values

        System.out.println(map);
    }
}
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