I have a list of objects that I need to transform to a map where the keys are a function of each element, and the values are lists of another function of each element. Effec
Now with Java8 you can do it like:
static class Element {
final int f1;
final String f2;
Element(int f1, String f2) {
this.f1 = f1;
this.f2 = f2;
}
int f1() { return f1;}
String f2() { return f2; }
}
public static void main(String[] args) {
List elements = new ArrayList<>();
elements.add(new Element(100, "Alice"));
elements.add(new Element(200, "Bob"));
elements.add(new Element(100, "Charles"));
elements.add(new Element(300, "Dave"));
elements.stream()
.collect(Collectors.groupingBy(
Element::f1,
Collectors.mapping(Element::f2, Collectors.toList())
))
.forEach((f1, f2) -> System.out.println("{"+f1.toString() + ", value="+f2+"}"));
}