Java 8 – streaming with objects and raw wrappers
I am using the Java 8 stream and trying to modify the object content in the foreach terminal operation
The problem I face here is that I can modify the contents of the list < employee > object, but I can't modify the contents of the list < integer >
The code snippet is as follows:
public static void streamExample() { List<Employee> listemp = Arrays.asList(new Employee()); listemp.stream().forEach(a -> a.setEmptName("John Doe")); listemp.stream().forEach(System.out::println); List<Integer> listInteger = Arrays.asList(2,4,6,8,12,17,1234); listInteger.stream().filter(v -> v % 2 == 0).forEach(a -> a=a+1); listInteger.stream().forEach(System.out::println); }
I want to know that the change is not reflected in the list because the integer object is unboxed when performing the a = a 1 operation, but I'm not sure
Solution
You don't have the best way to use stream Treat each step in the stream as modifying an existing (or creating a new) element and return it to the stream Finally, you will receive the final result, and you can use one of the final methods to finalize (and actually run) the stream:
List<Integer> listInteger = Arrays.asList(2,1234); listInteger.stream().filter(v -> v % 2 == 0).forEach(a -> a = a + 1); listInteger.stream().forEach(System.out::println);
Here is the initial array You want to do the following:
>Filter out some elements (this is not the last step); > Print the filtered elements (this is the last step)
To do this, you do not have to create streams. Net twice Use one:
Stream.of(2,1234) // create stream (there're many way to do it) .filter(v -> v % 2 == 0) // filter out required elements .map(v -> v + 1) // transform elements using given rule .forEach(System.out::println); // finalize stream with printing out each element separately
Note: stream Of (...) create a stream, then we add two steps to the stream filter and map, and then use foreach to complete or start to create the stream