Java Stream collects a map that contains a list

I want to create Mapfrom Listof Pointand have inside the map all the entries from the list mapped to the same parentId.

Map<Long, List<Point>> pointByParentId = chargePoints.stream()
    .collect(Collectors.toMap(Point::getParentId, c -> c));
+4
source share
3 answers

TL; DR:

To collect in Map, which contains one value by key ( Map<MyKey,MyObject>), use Collectors.toMap().
> To collect in Map, which contains several values ​​using the key ( Map<MyKey, List<MyObject>>), use Collectors.groupingBy().


Collectors.toMap ()

We write:

chargePoints.stream().collect(Collectors.toMap(Point::getParentId, c -> c));

The returned object will have a type Map<Long,Point>.
Take a look at the function Collectors.toMap()you are using:

Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper)

Collector Map<K,U>, K U - , . Point::getParentId , c Point. Map<Long,Point> , collect() .

Collectors.toMap() javadoc :

Collector, Map, .

( Object.equals(Object)), IllegalStateException , , Point : parentId.

, toMap(Function, Function, BinaryOperator), . parentId. parentId.


Collectors.groupingBy()

, Collectors.groupingBy(), :

public static <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier) 

:

, "group by" T, .

Function.
Function Point (type ), Point.getParentId(), parentId.

, :

Map<Long, List<Point>> pointByParentId = 
                       chargePoints.stream()
                                   .collect(Collectors.groupingBy( p -> p.getParentId())); 

:

Map<Long, List<Point>> pointByParentId = 
                       chargePoints.stream()
                                   .collect(Collectors.groupingBy(Point::getParentId));
+11

Collectors.groupingBy - , , , Function, , .

Map<Long, List<Point>> pointByParentId = chargePoints.stream()
    .collect(Collectors.groupingBy(Point::getParentId));
+3

The following code does this stuff. Collectors.toList()is standard, so you can skip it, but in case you want to have one Map<Long, Set<Point>> Collectors.toSet().

Map<Long, List<Point>> map = pointList.stream()
                .collect(Collectors.groupingBy(Point::getParentId, Collectors.toList()));
+3
source

Source: https://habr.com/ru/post/1681941/


All Articles