Java8 thread grouping and sorting by total sum
Given the 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 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 they are sorted by the total of noThings for one parent, and then by noThings.
So I end
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 match it by parentKey and noThings sum
Map<Integer, Integer> totalNoThings = colns .stream() .collect( Collectors.groupingBy( Something::getParentKey, Collectors.summingInt(ClientCollectionsReceived::getNoThings)));
I thought that maybe wrapping my class "Something" and with the total of the parent key might work in some way.
class SomethingWrapper {
private int totalNoThingsPerClient;
private Something something;
}
But that seems like a lot of work and not very elegant.
Any comments / ideas would be greatly appreciated.
+3
source to share
2 answers
Well, you've already done the bulk of the work gathering summary information.
Map<Integer, Integer> totalNoThings = somethings.stream() .collect(Collectors.groupingBy(Something::getParentKey, Collectors.summingInt(Something::getNoThings)));
then all you have to do is use this information in the sort operation:
List<Something> sorted=somethings.stream().sorted(
Comparator.comparing((Something x)->totalNoThings.get(x.getParentKey()))
.thenComparing(Something::getNoThings).reversed())
.collect(Collectors.toList());
+2
source to share
Actually a small tweak needed to be done, not totalNoThings.get, it was totalNothings.indexOf
So the final soln. was
List<Integer> totalNoThings
= somethings.stream()
.collect(Collectors.groupingBy(Something::getParentKey,
Collectors.summingInt(Something::getNoThings)))
.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
List<Something> sorted
= somethings.stream().sorted(
Comparator.comparing(
(Something obj)->totalNoThings.indexOf(
obj.getParentKey()))
.thenComparing(Something::getNoThings).reversed())
.collect(Collectors.toList());
0
source to share