Rus*_*ord 5 arrays java-8 java-stream
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
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?
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);
Run Code Online (Sandbox Code Playgroud)
If you want to collect into int[]
int[] ages = persons.stream()
.mapToInt(Person::getAge)
.distinct()
.toArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10240 次 |
| 最近记录: |