6

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?

1
  • If you read what you wrote it would be on the lines of, create a stream of people, then find distinct values amongst them, follow with mapping them to Integer and finally collect these as the result. Revisit this thought and see what all you have to rectify, that might help. Commented Jan 21, 2021 at 4:10

3 Answers 3

7

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.