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

时间:2019-05-12 20:26:22

标签: java java-8 sum java-stream nested-lists

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

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

我的问题是我嵌套了列表,我想获得一个列表。

我上了这个课:

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最少的sumPoweranotherListCompetitor却具有最大sumPower的东西?

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


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

如何获取这些列表?

1 个答案:

答案 0 :(得分:1)

您可以使用此:

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