I am new to java 8.I want to get the list of id of employees with a specific age given in list .
I actually want to use java 8 features to do this but I am unable to understand how to do use map and collect functions to get the desired output.
The expected output is as follows:
Eg-
20-1,5
40-2
30-3
50-4
I also want if we can make custom class with a list of ids.my real scenerio is based on custom objects.where i am retrieving certain values based on a unique value in a list.
The code is below
public class Emp {
int id;
int age;
public Emp(int id, int age) {
this.id = id;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Demo {
public static void main(String args[]) {
List list = new ArrayList();
list.add(new Emp(1, 20));
list.add(new Emp(2, 40));
list.add(new Emp(3, 30));
list.add(new Emp(4, 50));
list.add(new Emp(5, 20));
List l = list.stream().map(t -> t.getAge()).distinct().collect(Collectors.toList());
System.out.print(l);
}
}
解决方案
What you want is to group them, done by Collectors.groupingBy.
Map> map =
list.stream().collect(Collectors.groupingBy(Emp::getAge,
Collectors.mapping(Emp::getId, Collectors.toList())));
System.out.println(map); // {50=[4], 20=[1, 5], 40=[2], 30=[3]}

2837

被折叠的 条评论
为什么被折叠?



