List of ids from a list of age using java 8

I'm new to java 8. I want to get a list of employee IDs with a specific age given in the list.

I really want to use java 8 functions for this, but I can't figure out how to use the map and collect the functions to get the desired result.

The expected output looks like this:

Eg-

20-1,5

40-2

30-3

50-4

      

I also wish that we could create our own class with the ids.my list. real scenerio is based on custom objects. Where I am getting specific values ​​based on the unique value in the list.

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

      

+3


source to share


1 answer


What you need is group

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

      

+2


source







All Articles