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

get List from with maximum and minimum sum from (nested List) List of List using Java 8

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

Find maximum, minimum, sum and average of a list in Java 8

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

我有这个 class:

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>> 有没有可能用最小的 sumPower 得到 minListCompetitor 而用最大的 sumPower 得到 anotherListCompetitor

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

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

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