John Baum
John Baum

Reputation: 3331

Predicate in conjunction with a map in java8

Is there an easier/more succinct way than the below to use a predicate within a map with Java8?

public static void main(String[] args) {
        List<Integer> test = new ArrayList<>();
        test.add(1);
        test.add(2);
        test.add(3);
        test.add(4);

        List<Integer> test2 = test.stream()
            .map(i -> { if (i % 2 == 0) return i; else return 0;})
            .collect(toList());

        for (int i = 0; i < test2.size(); i++)
        {
            System.out.println(test2.get(i));
        }
    }

Output:
0
2
0
4

Essentially, I want to only transform members of my test list if they are odd.

Upvotes: 3

Views: 1932

Answers (2)

Andreas
Andreas

Reputation: 159086

Succinct version of your code:

List<Integer> test = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

List<Integer> test2 = test.stream()
                          .map(i -> i % 2 == 0 ? i : 0)
                          .collect(toList());
test2.forEach(System.out::println);

Upvotes: 3

Lachezar Balev
Lachezar Balev

Reputation: 12021

This one?

IntStream.rangeClosed(1, 4).map(i -> i % 2 == 0 ? i : 0).forEach(System.out::println);

Or if you want only even numbers in the stream (e.g. starting from 2) why not this one?

IntStream.iterate(2, i -> i + 2).limit(2).forEach(System.out::println);

Upvotes: 1

Related Questions