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);
}
}
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);
}
}