已过滤列表值的仅一个值列表 [英] List of Only One Single value of Filtered List Value

查看:65
本文介绍了已过滤列表值的仅一个值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to do divide and conquers to solve this question

在我的问题结合列表子集,Java子集生成列表之前,我已经有了此类.

I have this class before shown in my question Generate List with Combination of Subset of List, Java

我有一个名为竞争者"的类,具有类型",名称"和权限".

I have a class named Competitor, with Type, Name and Power.

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
  }
}

我试图用类型值创建一个列表:

I was trying to create a List with the types values :

    // 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!

如何从列表listCompetitors中创建仅单个项目type的列表?

How create a List of only single item type from the list listCompetitors?

推荐答案

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

You just want distinct values, for that you have to use a Set. Here's how it looks.

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

这篇关于已过滤列表值的仅一个值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆