Java: How to work with streams
Filter a list and process each element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
products.stream() | |
.filter( p -> p.getCASNumber() != null ) | |
.forEach( p -> System.out.println(p.getProductName()) ); | |
Filter a list and collect the elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<Product> productsWithCasNumber = products.stream() | |
.filter( p -> p.getCASNumber() != null ) | |
.collect( Collectors.loList() ); |
Transform a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<String> productNames = products.stream() | |
.map( p -> p.getProductName() ) //.map( Product::getProductName ) | |
.collect( Collectors.toList() ); |
Reduce a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double maxPrice = products.stream() | |
.map( p -> p.getProductPrice() ) //.map(Product::getProductPrice) | |
.reduce( 0.0, (calcValue, currentValue) -> Math.max(calcValue, currentValue) ); | |
//.reduce(0.0, Math::max) | |
Comments
Post a Comment