Convert a List of Objects from One Type to Another Using Lambda Expression

Lambda expression to add objects from one list to another type of list

If you define constructor OtherObj(String name, Integer maxAge) you can do it this java8 style:

myList.stream()
.map(obj -> new OtherObj(obj.getName(), obj.getMaxAge()))
.collect(Collectors.toList());

This will map all objects in list myList to OtherObj and collect it to new List containing these objects.

How to convert list of object to another list object using streams?

Simple use map() method in stream api and collect results:

  List<Emp> employe = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
List<Emp> employeRise = employe.stream()
.map(emp -> new Emp(emp.getId(), emp.getSalary * 100))
.collect(Collectors.toList());
employeRise.stream()
.forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));

Select a List from another List Using Lambda Expression

You're looking for SelectMany to flatten a list of lists.

public List<Product> SelectManyExample(List<Products> products)
{
return products.SelectMany(prds => prds.ProductList).ToList();
}


Related Topics



Leave a reply



Submit