排序给出一个Java类的东西java8流分组和总金额
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;
}
}
我有一些对象的列表
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)
);
我希望能够对它们进行排序,以使他们按每个父对象的noThings和noThings的累积和排序。
所以,我结束了
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)
);
我知道,通过parentKey映射它和空话的总和
Map<Integer, Integer> totalNoThings = colns
.stream()
.collect(
Collectors.groupingBy(
Something::getParentKey,
Collectors.summingInt(ClientCollectionsReceived::getNoThings)));
我想,也许包裹我的东西类,并具有总每父母键可能在某种程度上起作用。
class SomethingWrapper {
private int totalNoThingsPerClient;
private Something something;
}
但它看起来很多工作,而不是很优雅。
任何意见/想法将不胜感激。
List<Something> sorted=somethings.stream().sorted(
Comparator.comparing((Something x)->totalNoThings.get(x.getParentKey()))
.thenComparing(Something::getNoThings).reversed())
.collect(Collectors.toList());
谢谢!我正准备在一段代码摔角后发布答案!我的解决方案不如您的解决方案,但遵循相同的逻辑。 – IncompleteCoder