[英]list of id from a list of age using java 8
I am new to java 8.I want to get the list of id of employees with a specific age given in list . 我是java的新手。我想获得列表中给出的具有特定年龄的员工的id列表。
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. 我实际上想要使用java 8功能来做到这一点,但我无法理解如何使用map和collect函数来获得所需的输出。
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. 我还想要,如果我们可以使用ids列表制作自定义类。我的真实场景基于自定义对象。我在基于列表中的唯一值检索某些值。
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<Emp> list = new ArrayList<Emp>();
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<Integer> 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
. 你想要的是将它们group
,由Collectors.groupingBy
完成。
Map<Integer, List<Integer>> 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]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.