Skip to content

Instantly share code, notes, and snippets.

@ru-rocker
Last active December 18, 2016 13:04
Show Gist options
  • Save ru-rocker/933ba2015fe674103401bcbdd9882237 to your computer and use it in GitHub Desktop.
Save ru-rocker/933ba2015fe674103401bcbdd9882237 to your computer and use it in GitHub Desktop.
Sample usage of reduce operation in Java Stream API with one single parameter
Car car1 = new Car("BMW", "Red", 35000d);
Car car2 = new Car("Ford", "Yellow", 25000d);
Car car3 = new Car("Toyota", "Red", 10000d);
Car car4 = new Car("BMW", "Green", 35500d);
List<Car> cars = Arrays.asList(car1, car2, car3, car4);
//append all model into single line of string
cars.stream()
.map(c1 -> c1.getModel())
.distinct()
.reduce((s1, s2) -> s1 + "|" + s2)
.ifPresent(System.out::println);
//Output: BMW|Ford|Toyota
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment