Last active
December 15, 2016 12:47
-
-
Save ru-rocker/2ced09ee17d2c4937e198312bd74e225 to your computer and use it in GitHub Desktop.
Java 8 Stream Collectors Snippet
This file contains 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
Car car1 = new Car("BMW","Red", 35000d); | |
Car car2 = new Car("BMW","Green", 35500d); | |
Car car3 = new Car("Ford","Yellow", 25000d); | |
Car car4 = new Car("Toyota","Red", 10000d); | |
//populate car model list whose have red values | |
List<String> redCars = Stream.of(car1, car2, car3, car4) | |
.filter(s -> s.getColor().equals("Red") ) //get all cars with red values | |
.map(c -> c.getModel()) //map to get the model only | |
.collect(Collectors.toList()); | |
System.out.println(redCars); //Output: [BMW, Toyota] | |
//group car by its model | |
Map<String, List<Car>> carByModel = | |
Stream.of(car1, car2, car3, car4) | |
.collect(Collectors.groupingBy(c -> c.getModel())); | |
carByModel.forEach( | |
(model, car) -> System.out.format("Model %s: %s\n", model, car) ); | |
/*Output: | |
Model Toyota: [Car (model=Toyota, color=Red)] | |
Model Ford: [Car (model=Ford, color=Yellow)] | |
Model BMW: [Car (model=BMW, color=Red), Car (model=BMW, color=Green)] | |
*/ | |
//get average price for all cars | |
Double averagePrice = | |
Stream.of(car1, car2, car3, car4) | |
.collect(Collectors.averagingDouble( c -> c.getPrice() )); | |
System.out.println(averagePrice); //output: 26375.0 | |
//Get the price summary statistics | |
DoubleSummaryStatistics stats = | |
Stream.of(car1, car2, car3, car4) | |
.collect(Collectors.summarizingDouble( c -> c.getPrice() )); | |
System.out.println(stats);//output: DoubleSummaryStatistics{count=4, sum=105500.000000, min=10000.000000, average=26375.000000, max=35500.000000} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment