John Baum John Baum - 1 month ago 7
Java Question

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.

Answer

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.stream().forEach(System.out::println);
Comments