Java – an elegant way to use flatmap in flatingby
So I have a piece of code. I'm iterating over a data list Each is a reportdata, which contains a case with long caseid and a rule Each award has one or more payments I want to use the map with caseid as the key and the payment group as the value (that is, map < long, set < payments > >)
Cases are not unique between lines, but cases are
In other words, I can have several lines with the same case, but they will have unique rules
The following code provides me with a map < < long, set < < payments > > which is almost what I want, but I have been trying to find the correct way to find the final set of flatmap in a given context I've been working on a solution that uses this mapping to make logic work, but I really want to fix the algorithm to correctly combine this set of payments into a set instead of creating a set
Although using java stream for flatmapping seems to be a hot topic, I have been searching and can't find the same type of iteration problem
rowData.stream() .collect(Collectors.groupingBy( r -> r.case.getCaseId(),Collectors.mapping( r -> r.getRuling(),Collectors.mapping(ruling-> ruling.getPayments(),Collectors.toSet() ) )));
Solution
Another jdk8 solution:
Map<Long,Set<Payment>> resultSet = rowData.stream() .collect(Collectors.toMap(p -> p.Case.getCaseId(),p -> new HashSet<>(p.getRuling().getPayments()),(l,r) -> { l.addAll(r);return l;}));
Alternatively, starting with jdk9, you can use the flatmapping collector:
rowData.stream() .collect(Collectors.groupingBy(r -> r.Case.getCaseId(),Collectors.flatMapping(e -> e.getRuling().getPayments().stream(),Collectors.toSet())));