Java 8 Streams - Get distinct integers from object list as an array

Viewed 3169

I'm struggling to work out how to get the distinct integers from an object list as an array using Streams.

Consider I have the below class:

public class Person{

    private int age;
    private double height;

    public Person(int age, double height) {
        this.age= age;
        this.height = height;
    }

    public int getAge() {
        return age;
    }

    public double getHeight() {
        return height;
    }
}

Then consider that have a populated list of these objects e.g. List<Person> people.

My question is, how do I use Java streams to extract the distinct ages into a Int array?

What I have so far is:

List<Integer> distinctAge = people.stream().distinct().mapToInt().collect(Collectors.groupingBy(Person::getAge));

Obviously that doesn't compile but I'm hitting a wall as to where to go next.

Once I have this array, I'm planning to grab all the objects from the list which contain the distinct value - I assume this is also possible using Streams?

3 Answers

You can collect all ages using map and the call distinct for distinct values

Integer[] ages = persons.stream()
            .map(Person::getAge)
            .distinct()
            .toArray(Integer[]::new);

If you want to collect into int[]

int[] ages = persons.stream()
            .mapToInt(Person::getAge)
            .distinct()
            .toArray();

Better to use Set instead of using distinct as it improve performance.

Set<Integer> ages = persons.stream().map(Person::getAge).collect(Collectors.toSet());

My question is, how do I use Java streams to extract the distinct ages into a Int array?

Once I have this array, I'm planning to grab all the objects from the list which contain the distinct value - I assume this is also possible using Streams?

Paraphrasing this problem,

You need a Map<Integer,List> where key of the map is the age and the value is a List of Person of that particular age.

Map<Integer, List<Person>> agePersonMap =
        people.stream()
            .collect(Collectors.groupingBy(Person::getAge));
Related