簡體   English   中英

使用 Java 8 從(嵌套列表)列表列表中獲取列表的最大和最小總和

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

我正在檢查這些問題,但它沒有回答我的問題

如何使用 Java 從對象列表中獲取最小值和最大值 8
在 Java 8 中查找列表的最大值、最小值、總和和平均值

我的問題我有嵌套列表,我想獲得一個列表。

我有這個 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

現在,我想獲得具有最小power屬性總和的List<Competitor> <Competitor> 和具有最大總和的其他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>>是否有可能獲得具有最小sumPowerminListCompetitor和具有最大anotherListCompetitorsumPower

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM