I have a list
of Data
object
public class Data{
private String id;
private String sharedId;
}
How to convert this list
into Map<String,List<Data>>
, collecting the data object
sharing the same sharedId
together
I have tried to use this line of code, but no luck
Map<String,List<Data>> dataMap= Flux.fromIterable(list)
.collectMap(item-> item.getSharedId(),
item-> item);
CodePudding user response:
The following should work:
Map<String,List<Data>> dataMap =
list.stream().collect(groupingBy(Data::getSharedId));
CodePudding user response:
Stream API is not equal to Reactive API and they are not interchangeable.
Use Stream API for grouping into Map<String, List<Data>>
from List<Data>
:
Map<String,List<Data>> dataMap = list.stream()
.collect(Collectors.groupingBy(Data::getSharedId));
Using Reactive API to achieve you achieve Flux<GroupedFlux<String, Data>>
analogically or expand the structure using Map.Entry
:
Flux<GroupedFlux<String, Data>> groupedFlux = Flux.fromIterable(list)
.groupBy(Data::getSharedId);
Flux<Map.Entry<String, List<Data>>> groupedFlux = Flux.fromIterable(list)
.groupBy(Data::getSharedId)
.flatMap(group -> group
.collectList()
.map(listOfData -> Map.entry(group.key(), listOfData)));