I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.
This is how I would write it in Java 7 and below.
private Map&l
This can be done in 2 ways. Let person be the class we are going to use to demonstrate it.
public class Person {
private String name;
private int age;
public String getAge() {
return age;
}
}
Let persons be the list of Persons to be converted to the map
1.Using Simple foreach and a Lambda Expression on the List
Map> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));
2.Using Collectors on Stream defined on the given List.
Map> mapPersons =
persons.stream().collect(Collectors.groupingBy(Person::getAge));