JAVA年龄区间查找代码,使用java 8从年龄列表中的id列表

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]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值