Last active
December 18, 2016 13:33
-
-
Save ru-rocker/a40147495a1c7c2adf16aa13197bb290 to your computer and use it in GitHub Desktop.
Sample usage of reduce operation in Java Stream API with three parameters
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
String carModels = cars.parallelStream() | |
.map(c1 -> c1.getModel()) | |
.distinct() | |
.reduce("Renault", | |
(s1, s2) -> { | |
System.out.printf("s1: %s and s2: %s \n", s1, s2); | |
return s1 + "|" + s2; | |
}, | |
(com1, com2) -> { | |
System.out.printf("com1: %s and com2: %s \n", com1, com2); | |
int indexOf = com2.indexOf('|'); | |
if(indexOf > 0){ | |
return com1 + com2.substring(indexOf); //remove 'Renault|' for the second strint | |
} | |
return com1; | |
} | |
); | |
System.out.println(carModels); | |
// s1: Renault and s2: BMW | |
// s1: Renault and s2: Ford | |
// s1: Renault and s2: Toyota | |
// com1: Renault|Ford and com2: Renault|Toyota | |
// com1: Renault|BMW and com2: Renault|Ford|Toyota | |
// com1: Renault|BMW|Ford|Toyota and com2: Renault | |
// Renault|BMW|Ford|Toyota |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment