gpt4 book ai didi

java - 使用 Java 8 从(嵌套列表)列表中获取具有最大和最小总和的列表

转载 作者:行者123 更新时间:2023-11-30 10:03:58 29 4
gpt4 key购买 nike

我正在检查这些问题,但它没有回答我的问题

How to get minimum and maximum value from List of Objects using Java 8
Find maximum, minimum, sum and average of a list in Java 8

我的问题我有嵌套的List,我想获得一个List。

我有这门课:

public class Competitor {
private final int type;
private final String name;
private final int power;

public Competitor(int type, String name, int power) {
this.type = type;
this.name = name;
this.power = power;
}

public int getType() {
return type;
}

public String getName() {
return name;
}

public int getPower() {
return power;
}

@Override
public String toString() {
return "Competitor{" + "type=" + type + ", name=" + name + ", power=" + power + "} ";
}

}

现在我有一个 List<List<Competitor>>喜欢:

List<List<Competitor>> anotherListOfListCompetitor = new ArrayList<>();
anotherListOfListCompetitor.add(new ArrayList<>(
Arrays.asList(new Competitor(1, "Cat 00", 93), new Competitor(2, "Dog 18", 40), new Competitor(3, "Pig 90", 90)))); //93 + 40 + 90 = 223

anotherListOfListCompetitor.add(new ArrayList<>(
Arrays.asList(new Competitor(1, "Cat 23", 20), new Competitor(2, "Dog 30", 68), new Competitor(3, "Pig 78", 32)))); //20 + 68 + 32 = 120

anotherListOfListCompetitor.add(new ArrayList<>(
Arrays.asList(new Competitor(1, "Cat 10", 11), new Competitor(4, "Cow 99", 90)))); //11 + 90 = 101

现在,我想获得 List<Competitor>最小总和为 power属性(property)及其他List<Competitor>最大总和。

我知道减少...

List<Competitor> someListCompetitor = //populate the list

int sumPower = someListCompetitor.stream()
.map(competitor -> competitor.getPower())
.reduce(0, (a, b) -> a + b);

但是 List<List<Competitor>> 有可能吗?获得minListCompetitor最小sumPoweranotherListCompetitor最大 sumPower ?

List<Competitor> minListCompetitor = anotherListOfListCompetitor
.stream()... // which sum power is 101


List<Competitor> maxListCompetitor = anotherListOfListCompetitor
.stream()... // which sum power is 223

如何获取这些列表?

最佳答案

你可以使用这个:

List<Competitor> minListCompetitor = anotherListOfListCompetitor.stream()
.min(Comparator.comparingInt(l -> l.stream().mapToInt(Competitor::getPower).sum()))
.orElse(Collections.emptyList());

List<Competitor> maxListCompetitor = anotherListOfListCompetitor.stream()
.max(Comparator.comparingInt(l -> l.stream().mapToInt(Competitor::getPower).sum()))
.orElse(Collections.emptyList());

这会返回列表总和的 .min()/.max()。它使用您提供的代码的简化版本来计算总和。

如果你想在找不到最大值时抛出异常,你可以使用 .orElseThrow()

关于java - 使用 Java 8 从(嵌套列表)列表中获取具有最大和最小总和的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56103192/

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