String output = names.stream()
.sorted((name1, name2) -> {
String[] parts1 = name1.split(" ");
String lastName1 = parts1[parts1.length - 1];
String[] parts2 = name2.split(" ");
String lastName2 = parts2[parts2.length - 1];
return lastName2.compareTo(lastName1);
})
.map(name -> {
String[] parts = name.split(" ");
return parts[parts.length - 1];
})
.filter(lastName -> lastName.length() >= 5)
.reduce("", (accumulator, element) -> accumulator + element + ", ");
System.out.println("result: " + output);
This code snippet sorts and filters a list of names based on last names, concatenates them with a comma separator, and prints the result.
The reduce
operation is demonstrated here to concatenate strings together. If you want to count string characters instead, you can explore using reduce
with different data types.
Reusing operations
Creating a functional interface in Java allows for code reuse, especially when you have a complex operation like the string sorting shown above that needs to be used in multiple places.