Raju Raju - 1 year ago 146
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 Source

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 =