gpt4 book ai didi

筛选列表值的仅一个单个值的列表

转载 作者:行者123 更新时间:2023-12-01 00:38:37 24 4
gpt4 key购买 nike

我想做分而治之来解决这个问题

在我的问题 Generate List with Combination of Subset of List, Java 中显示之前,我有这门课

我有一个名为 Competor 的类,具有类型、名称和功率。

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
public class Game {
public static void main(String... args) {
List<Competitor> listCompetitors = new ArrayList<>();
listCompetitors.add(new Competitor(1, "Cat 00", 93));
listCompetitors.add(new Competitor(1, "Cat 10", 11));
listCompetitors.add(new Competitor(1, "Cat 23", 20));

listCompetitors.add(new Competitor(2, "Dog 61", 54));
listCompetitors.add(new Competitor(2, "Dog 18", 40));
listCompetitors.add(new Competitor(2, "Dog 45", 71));
listCompetitors.add(new Competitor(2, "Dog 30", 68));

listCompetitors.add(new Competitor(3, "Pig 90", 90));
listCompetitors.add(new Competitor(3, "Pig 78", 32));

listCompetitors.add(new Competitor(4, "Cow 99", 90));

I want to obtain a List with values -> 1, 2, 3, and 4
}
}

我试图用类型值创建一个列表:
    // List with only types
List<Integer> listTypes = listCompetitors.stream().sorted(
Comparator.comparing(Competitor::getType)
).collect(
Collectors.toMap(Competitor::getType, Competitor::getType)
); // Does n't compile!



// List with only types
List<Integer> listTypes = listCompetitors.stream().sorted(
Comparator.comparing(Competitor::getType)
).collect(
Collectors.groupingBy(Competitor::getType)
); // Does n't compile!

如何创建仅包含单个项目的列表 type来自列表listCompetitors ?

最佳答案

您只需要不同的值,因为您必须使用 Set .这是它的外观。

Set<Integer> typeList = listCompetitors.stream()
.map(Competitor::getType)
.collect(Collectors.toSet());

关于筛选列表值的仅一个单个值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com