Collector in Java Stream API

Purpose

Story

public static List<Car> filterCars(List<Car> cars, String color) {
return cars.stream()
.filter(car -> car.getColor().equals(color))
.collect(Collectors.toList());
}
cars.stream().collect(Collectors.counting());
cars.stream().count();
cars.stream().collect(Collectors.maxBy((a, b) -> Integer.compare(a.getPrice() , b.getPrice())));
cars.stream().max(Comparator.comparingInt(Car::getPrice));
cars.stream().collect(Collectors.minBy(Comparator.comparing(Car::getPrice)))
cars.stream().min(Comparator.comparing(Car::getPrice));
cars.stream()
.filter(car -> car.getBrand().equals(brand))
.collect(Collectors.summarizingInt(Car::getPrice));
cars.stream()
.filter(car -> car.getBrand().equals(brand))
.map(car -> car.getPrice())
.reduce((a, b) -> a + b);
cars.stream()
.filter(car -> car.getBrand().equals(brand))
.collect(Collectors.reducing(0, Car::getPrice, Integer::sum));
String carNames = cars.stream()
.map(car -> car.getName())
.collect(Collectors.joining());
Map<String, List<Car>> listOfCarsByPriceRangeMap = cars.stream()
.collect(Collectors.groupingBy(car -> {
if (car.getPrice() <= 500000) {
return "BUDGET_FRIENDLY";
} else if (car.getPrice() <= 1000000) {
return "MID_RANGE";
} else {
return "EXPENSIVE";
}
}));
Map<String, List<Car>> listOfCarsByBrandMap = cars.stream()
.collect(Collectors.groupingBy(Car::getBrand));
Map<String, Map<String, List<Car>>> listOfCarsByPriceRangeMap = cars.stream()
.collect(Collectors.groupingBy(Car::getBrand, Collectors.groupingBy(car -> {
if (car.getPrice() <= 500000) {
return "BUDGET_FRIENDLY";
} else if (car.getPrice() <= 1000000) {
return "MID_RANGE";
} else {
return "EXPENSIVE";
}
})));
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store