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.
See more on this question at Stackoverflow