I have a Person ArrayList
List<Person> personList = getPersonList();
And I want to create a map of Map<String, List<Long>>
key based on Person::getDepartment and value based on a List<Long>
of timestamps Person::getTimestamp
There are multiple Person records in the List<Person> personList
, so I need to remove duplicates on Person::getDepartment
, but since a Map doesn't let key duplicates, that should not be a problem, i think.
I can do that perfect with a forach loop but my question is can I do that with only one stream?
public class Person {
private String department;
private long timestamp;
//getters and setters
}
In the collect, use groupingBy()
to group Person
by department and mapping()
to map the Person
to its timestamp.
Map<String, List<Long>> map =
personList.stream()
.collect(groupingBy(
Person::getDepartment,
mapping(Person::getTimestamp, toList())
)
);
And add these imports :
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
or just :
import static java.util.stream.Collectors.*;
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.