0
\$\begingroup\$

I wrote this code to check the even numbers from the List. After finding even number I twice the even numbers with the help of Map and then find the sum of each even number after making it double by use of the reduce method.

import java.util.Arrays;
import java.util.List;
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(
numbers.stream()
 .filter(e -> e % 2 == 0)
 .map( e -> e * 2)
 .reduce(0, Integer::sum));
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 20, 2016 at 5:31
\$\endgroup\$
1
  • \$\begingroup\$ Try to express the desired sum as formula of your N of the integer range and you don't need no Lambdas at all :) \$\endgroup\$ Commented Oct 20, 2016 at 9:27

1 Answer 1

3
\$\begingroup\$

Have you come across the IntStream? I'd use that for numerical operations rather than the boxed version Stream<Integer>.

answered Oct 20, 2016 at 5:36
\$\endgroup\$
2
  • \$\begingroup\$ System.out.println(numbers.stream().filter(e -> e % 2 == 0).mapToInt( e -> e * 2).sum()); I change the map to mapToInt and remove that box Integer::sum to sum(). \$\endgroup\$ Commented Oct 20, 2016 at 5:39
  • 3
    \$\begingroup\$ Or one step further (assuming the List is not absolutely necessary): IntStream.rangeClosed(1, 9).filter(e -> e % 2 == 0).map(e -> e * 2).sum() \$\endgroup\$ Commented Oct 20, 2016 at 5:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.