Member-only story
Java Streams
- Added in Java 8
- Wrapper around a data source, allowing us to operate on that data source and make bulk processing fast
- Stream doesn’t store data (not a data structure)
- Does not modifying underling data source
- java.util.stream supports functional style operations such as map-reduce transformations on collections
Stream Creation:
Below are 3 popular methods to create a java Stream.
1)
collection.stream() -: eg: emparray.stream()
2)
Stream.of(emparray[0], emparray[1], emparray[2]);
3)
StreamBuilder empStreamBuilder = Stream.builder(); empStreamBuilder.accept(emparray[0]); empStreamBuilder.accept(emparray[1]); empStreamBuilder.accept(emparray[2]);
Stream empStream = empStreamBuilder.build();
Stream Operations:
forEach — loops over the stream elements, calling the supplied function on each element.
The below code effectively calls incrementSalary on each element of empList.
@Test public void whenIncrementSalaryForEachEmployee_thenApplyNewSalary() { empList.stream().forEach(e -> e.incrementSalary(10.00)); assertThat(empList, contains( hasProperty("salary",110000), hasProperty("salary", 210000), hasProperty("salary", 3100000) ));