Collections – java8 converts lists to map >
•
Java
I have a list < person > object and want to convert it to map < integer. The keyword of the list < person > > map represents a person's property level It may have multiple person objects with the same level in the source list. In this case, I want to group them all into the list to compare the corresponding levels in the resulting map
So far, I have the following code
public class PersonMain
{
public static void main(String[] args)
{
Person person1 = new Person();
person1.setName("person1");
person1.setGrade(1);
Person person2 = new Person();
person2.setName("person2");
person2.setGrade(2);
Person person3 = new Person();
person3.setName("person3");
person3.setGrade(1);
List<Person> persons = Arrays.asList(person1,person2,person3);
Map<Integer,List<Person>> personsMap = persons.stream()
.collect(Collectors.toMap(Person::getGrade,PersonMain::getPerson,PersonMain::combinePerson));
System.out.println(personsMap);
}
private static List<Person> getPerson(Person p)
{
List<Person> persons = new ArrayList<>();
persons.add(p);
return persons;
}
private static List<Person> combinePerson(List<Person> oldVal,List<Person> newVal)
{
oldVal.addAll(newVal);
return oldVal;
}
}
Is there a better way to achieve this?
Solution
Your current solution is good, but using the groupingby collector is more intuitive:
Map<Integer,List<Person>> personsMap =
persons.stream()
.collect(Collectors.groupingBy(Person::getGrade));
This overload of the groupingby collector is very simple, because it only requires a classifier (person:: getgrade) function, which will extract the key to group the streaming objects
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
