List<Integer> integers = Arrays.asList(10, -5, 3, 7, 20, -30, -1);
final int bound = 10;
How can i do these steps(square and sum) by Lambda Expresion?
List<Integer> integers = Arrays.asList(10, -5, 3, 7, 20, -30, -1);
final int bound = 10;
How can i do these steps(square and sum) by Lambda Expresion?
Print with forEach:
integers.stream()
.filter(value -> value <= bound && value >= -bound)
.forEach(value -> System.out.print(value +" "));
Sum:
int sum = integers.stream()
.filter(value -> value <= bound && value >= -bound)
.mapToInt(value -> value*value)
.sum();
Try this. It takes the elements and streams them, applies your filter and then maps each element to its square. The boxed operation maps to an Integer so it can be collected to the list.
List<Integer> squares = IntStream.of(10, -5, 3, 7, 20, -30, -1)
.filter(value -> value <= bound && value >= -bound)
.map(a -> a * a)
.boxed()
.collect(Collectors.toList());
System.out.println(squares);
Prints
[100, 25, 9, 49, 1]
You could also have broken it up into parts.
Establish the stream
IntStream integers = IntStream.of(10, -5, 3, 7, 20, -30, -1);
Now apply it.
List<Integer> squares = integers.filter(value -> value <= bound && value >= -bound)
.map(a -> a * a)
.boxed()
.collect(Collectors.toList());
System.out.println(squares);
To get their sum, just do this.
int sum = integers.filter(value -> value <= bound && value >= -bound)
.map(a -> a * a)
.sum();
System.out.println(sum);
Prints
184