Skip to content

Instantly share code, notes, and snippets.

@ru-rocker
Last active December 18, 2016 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ru-rocker/a40147495a1c7c2adf16aa13197bb290 to your computer and use it in GitHub Desktop.
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
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