Raju Raju - 4 months ago 70
Java Question

Java 8 Lambda expression to collect only one field from List of Objects

I have class Emp

class Emp {
Integer id;
String name;
}


And a List of Emp objects,

List<Emp> empList=new ArrayList<>();


How can I write a Lambda expression to create a list of Emp Id's ?

List<Integer> idList = (Some lambda expression)

Answer

You could use the map method with a lambda to get the id:

List<Integer> idList = 
    empList.stream().map(e -> e.getId()).collect(Collectors.toList());

Or with a method reference:

List<Integer> idList = 
    empList.stream().map(Employee::getId).collect(Collectors.toList());