gpt4 book ai didi

java - 如何使用流获取多个属性具有最大值的对象?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:10 25 4
gpt4 key购买 nike

假设我有一群恶棍。它们的特点是它们有多好、有多坏或有多丑。

static class Villain {
String name;
int good;
int bad;
int ugly;

Villain(String name, int good, int bad, int ugly) {
this.name = name;
this.good = good;
this.bad = bad;
this.ugly = ugly;
}
}

好吧,认识一下这帮人:

List<Villain> villains = new ArrayList<>();
villains.add(new Villain("Bob", 2, 2, 1));
villains.add(new Villain("Charley", 2, 1, 2));
villains.add(new Villain("Dave", 2, 1, 1));
villains.add(new Villain("Andy", 2, 2, 2));
villains.add(new Villain("Eddy", 1, 2, 2));
villains.add(new Villain("Franz", 1, 2, 1));
villains.add(new Villain("Guy", 1, 1, 2));
villains.add(new Villain("Harry", 1, 1, 1));

我想做的是,我想弄清楚谁是最好的,最坏的,最丑的。我的意思是找出谁是最好的。如果平局,谁是最差的。如果平局,谁最丑。

我已经成功地做到了,代码如下。

List<Villain> bestVillains = villains
.stream()
.collect(groupingBy(v -> v.good, TreeMap::new, toList()))
.lastEntry()
.getValue()
.stream()
.collect(groupingBy(v -> v.bad, TreeMap::new, toList()))
.lastEntry()
.getValue()
.stream()
.collect(groupingBy(v -> v.ugly, TreeMap::new, toList()))
.lastEntry()
.getValue();

这确实会导致 List<Villain>只有一个成员:安迪。他真的是最好的,最坏的,最丑的!

但是,我有相当多的代码重复、收集值、再次将它们转换为流等。关于如何清理它的任何建议?

JVM 是如何处理的。顺序地还是引擎盖下发生了一些魔法?

最佳答案

So the idea is that it first looks at which has the highest value for good, then (in case of a tie) which has the highest value for bad, then (if it is still not decisive) which has the highest value for 'ugly'

您更愿意使用以下 ComparatorVillian 进行排序:

Comparator<Villain> villainComparator = Comparator.comparingInt(Villain::getGood)
.thenComparingInt(Villain::getBad)
.thenComparingInt(Villain::getUgly);

Villain result = villains.stream()
.max(villainComparator)
.orElse(null);

关于java - 如何使用流获取多个属性具有最大值的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54594265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com