Given a java class Something
class Something {
private int parentKey;
private String parentName;
private int childKey;
private int noThings;
public Something(int parentKey, String parentName, int childKey,
int noThings) {
this.parentKey = parentKey;
this.parentName = parentName;
this.childKey = childKey;
this.noThings = noThings;
}
public int getParentKey() {
return this.parentKey;
}
public int getNoThings() {
return this.noThings;
}
}
I have a list of something objects
List<Something> somethings = newArrayList(
new Something(425, "Lemon", 44, 23),
new Something(123, "Orange", 125, 66),
new Something(425, "Lemon", 11, 62),
new Something(123, "Orange", 126, 32),
new Something(323, "Lime", 25, 101),
new Something(123, "Orange", 124, 88)
);
I want to be able to sort them so that the they are sorted by the cumulative sum of the noThings per parent object and then by the noThings.
So that I end up with
List<Something> sortedSomethings = newArrayList(
new Something(123, "Orange", 124, 88),
new Something(123, "Orange", 125, 66),
new Something(123, "Orange", 126, 32),
new Something(323, "Lime", 25, 101),
new Something(425, "Lemon", 11, 62),
new Something(425, "Lemon", 44, 23)
);
I know that to map it by parentKey and sum of noThings is
Map<Integer, Integer> totalNoThings = colns
.stream()
.collect(
Collectors.groupingBy(
Something::getParentKey,
Collectors.summingInt(ClientCollectionsReceived::getNoThings)));
I thought that maybe wrapping my Something class and having the total per Parent Key might work in someway.
class SomethingWrapper {
private int totalNoThingsPerClient;
private Something something;
}
But it seems like a lot of work and not very elegant.
Any observations/ ideas would be gratefully appreciated.
Well, you already did the main work by collecting the aggregate information
then all you need to do is utilizing these information in a sort operation: