One of the missing features in the Streams API is the \"partition by\" transformation, for example as defined in Clojure. Say I want to reproduce Hibernate\'s fetch join
For those of you who just want to partition a stream, there are mappers and collectors for that.
class Person {
String surname;
String forename;
public Person(String surname, String forename) {
this.surname = surname;
this.forename = forename;
}
@Override
public String toString() {
return forename;
}
}
class Family {
String surname;
List members;
public Family(String surname, List members) {
this.surname = surname;
this.members = members;
}
@Override
public String toString() {
return "Family{" + "surname=" + surname + ", members=" + members + '}';
}
}
private void test() {
String[][] data = {
{"Kray", "Ronald"},
{"Kray", "Reginald"},
{"Dors", "Diana"},};
// Their families.
Stream families = Arrays.stream(data)
// Build people
.map(a -> new Person(a[0], a[1]))
// Collect into a Map> as families
.collect(Collectors.groupingBy(p -> p.surname))
// Convert them to families.
.entrySet().stream()
.map(p -> new Family(p.getKey(), p.getValue()));
families.forEach(f -> System.out.println(f));
}