使用java 8从年龄列表中的id列表 [英] list of id from a list of age using java 8

查看:148
本文介绍了使用java 8从年龄列表中的id列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java的新手。我想获得列表中给定的特定年龄的员工的id列表。

I am new to java 8.I want to get the list of id of employees with a specific age given in list .

我实际上想要使用java 8这样做的功能,但我无法理解如何使用map和collect函数来获得所需的输出。

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.

预期输出如下:

Eg-

20-1,5

40-2

30-3

50-4

我还想要,如果我们可以使用ids列表制作自定义类。我的真实场景基于自定义对象。我在基于列表中的唯一值检索某些值。

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.

代码低于

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


推荐答案

什么你想要的是 group 他们,由 Collectors.groupingBy 完成。

What you want is to group them, done by 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]}

这篇关于使用java 8从年龄列表中的id列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆