简体   繁体   中英

How convert list from one to another type using lameda Expression java

I have a list of Entities Employee(Class) which has fields empid, empname, emprole.salary

List<Employee>= getting from database

I want to convert it into model list Person(Class) having fields empname, emprole, salary

List<Person> person = new ArrayList<Person>();

I am able to convert using a for loop. However, I want to convert it using lambda expression.

Assuming you've got a suitable constructor, it should be as simple as:

List<Person> people = employees
    .stream() // View the list as a stream
    .map(e -> new Person(e.getId(), e.getName(), e.getRole().getSalary()))
    .collect(Collectors.toList());

Note that if that's all you're doing with the list of employees, that may well mean you've fetched more data than you actually need. You should look at what the queries are doing and consider tweaking them to only return what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM