首页 > 解决方案 > 使用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>的最小总和。powerList<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()... // wich sum power is 101


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

如何获取这些列表?

标签: javajava-8sumjava-streamnested-lists

解决方案


你可以使用这个:

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().


推荐阅读