0
        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?

2

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

what if i wanted to keep it in for loop, then mapInt doesnt work
make it return a list, see the answer of @WJS, it will work
1

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

Comments