Probably it's late but I like to share an improved idea to this problem. This is basically the same of @Vitalii Fedorenko's answer but more handly to play around.
You can just use the Collectors.groupingBy()
by passing the grouping logic as function parameter and you will get the splitted list with the key parameter mapping. Note that using Optional
is used to avoid the unwanted NPE when the provided list is null
public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
return Optional.ofNullable(list)
.orElseGet(ArrayList::new)
.stream()
.collect(Collectors.groupingBy(keyFunction));
}
Now you can groupBy anything with this. For the use case here in the question
Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);
Maybe you would like to look into this also Guide to Java 8 groupingBy Collector