Can I convert List <V> to Map <K, List <V>> without foreach?
I have a list of objects. Each object has a "date" property, and I need to convert this list to a map where the key is "date" and the value is "List of objects".
I can do this using a standard foreach, but is it possible with Java 8 and streams?
+3
Damian u
source
to share
2 answers
What's collect
with groupingBy
for:
Map<K, List<V>> groups = listOfVs.stream().collect(Collectors.groupingBy(V::getK));
+9
Eran
source
to share
You can use the API Stream
since Java 8 to group items in List
by date and put them in Map
like this:
Map<Date, List<YourObject>> collisions = yourObjectsList.stream().collect(Collectors.groupingBy(YourObject::getDate));
+4
CraigR8806
source
to share