我想通过分而治之来解决这个问题
在我的问题Generate List with Combination of Subset of List, Java
中显示之前,我已经上过此类课我有一个名为Competitor的类,具有类型,名称和功能。
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 + '}';
}
}
现在我填写列表
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
的列表?
答案 0 :(得分:4)
您只需要不同的值,为此必须使用Set
。看起来就是这样。
Set<Integer> typeList = listCompetitors.stream()
.map(Competitor::getType)
.collect(Collectors.toSet());
答案 1 :(得分:2)
根据拉文德拉的答案
// List with only types
List<Integer> typeList = new ArrayList<>(listCompetitors.stream()
.map(Competitor::getType)
.collect(Collectors.toSet()));
typeList.stream().forEach(System.out::println);
输出
1
2
3
4