I want to do divide and conquers to solve this question

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 + '}';
  }

}

Now I filling the 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
  }
}

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!

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

2 Answers

4
Ravindra Ranwala On Best Solutions

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());
2
chepe lucho On

Based on the answer of Ravindra

// List with only types
List<Integer> typeList = new ArrayList<>(listCompetitors.stream()
    .map(Competitor::getType)
    .collect(Collectors.toSet()));

typeList.stream().forEach(System.out::println);

The output

1
2
3
4