Andi Pavllo Andi Pavllo - 2 months ago 8
Java Question

Print modified list values using Java 8 Stream

Having a list like the following one

List<Integer> values = new ArrayList<Integer>();

values.add(1);
values.add(0);
values.add(1);
values.add(1);
values.add(0);


I want to print the elements
> 0
adding them a value, for example
10
, by using Java 8 Stream. For example:

values.stream()
.filter(val -> val > 0)
// HERE add 10
.forEach(System.out::println);


Is it possible to do that? If yes, how?

Answer

Use the map operation

values.stream()
      .filter(val -> val>0)
      .map(x -> x+10)
      .forEach(System.out::println);

If you need to keep the values, do

List<Integer> newValues = values.stream()
                                .filter(val -> val>0)
                                .map(x -> x+10)
                                .collect(Collectors.toList());
Comments