String output = names.stream()
.sorted((name1, name2) -> {
String[] parts1 = name1.break up(" ");
String lastName1 = parts1[parts1.length - 1];
String[] parts2 = name2.break up(" ");
String lastName2 = parts2[parts2.length - 1];
return lastName2.compareTo(lastName1);
})
.map(title -> {
String[] elements = title.break up(" ");
return elements[parts.length - 1];
})
.filter(lastName -> lastName.size() >= 5)
.scale back("", (accumulator, factor) -> accumulator + factor + ", ");
System.out.println("outcome: " + output);
This can concatenate all of the strings collectively, joined by a comma. (We’ll have a trailing comma that we might drop off the tip.)
scale back
provides us an fascinating take a look at a barely extra superior space of streams. Think about in the event you needed to depend the string characters and return an integer worth. How might you try this? The return worth of scale back
would wish to be an integer, however the accumulator
and factor
args are strings. I’ll go away that for an train, with this Stack Overflow query as one lead, and my introduction to Java stream gatherers as one other.
Reusing operations
We’ve had a reasonably good take a look at the way in which it feels to make use of and compose among the most vital Java purposeful operations. One other vital aspect is code reuse. Say you wanted to make use of that fancy string sorter in a number of locations. In Java, we might create a purposeful interface to share that operation: