java - 使用Java 8从(嵌套列表)列表列表中获取最大和最小总和的列表
问题描述
我正在检查这些问题,但它没有回答我的问题
如何使用 Java 8 从对象列表中获取最小值和最大值 在 Java 8 中 查找列表的最大值、最小值、总和和平均值
我的问题我有嵌套列表,我想获得一个列表。
我有这堂课:
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
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
具有最小sumPower
和anotherListCompetitor
最大的sumPower
?
List<Competitor> minListCompetitor = anotherListOfListCompetitor
.stream()... // wich sum power is 101
List<Competitor> maxListCompetitor = anotherListOfListCompetitor
.stream()... // wich 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()
.
推荐阅读
- powershell - How do i dynamically change file-names with Rename-Item?
- javascript - fs.readFileSync("./bank/"+client,'cp1251'); 正在抛出新的 ERR_INVALID_OPT_VALUE_ENCODING
- c# - 如何从 ObjectListView 中选定项目的特定列中获取数据?
- vba - 运行时错误 91,未设置对象,尝试自动下载电子邮件附件
- vb6 - 将 BLOB 保存到文档
- javascript - 在第一个结果中获取下拉列表的返回值 [object Object]。当我选择一个选项并工作时,它会改变。如何修复默认结果
- laravel - 部署 laravel + vuejs 到共享主机
- java - 使用 PreparedStatement 在 where 子句中传递字符串
- mysql - 加入两个集合并在 MongoDB 中更新
- c - libxml2 的解析问题:命名空间错误