Reputation: 277
In a part of a code I have the situation, the type of the collection is that I need:
Map<Specialization, List<SpecialistInfo>> specialistsMap = specialistsResponse
.getSpecialists()
.stream()
.collect(groupingBy(SpecialistInfo::getSpecializations));
But actually, that stream returns a Map<List<Specialization>, List<SpecialistInfo>>.
The getSpecialists()
method returns List<SpecialistInfo> specialists;
and every instance of SpecialistInfo
contains a list too. So, the method getSpecializations returns List<Specialization> specializations
I need to group my map into a Map<Specialization, List<SpecialistInfo>>
.
How it can be done via Stream API?
Upvotes: 0
Views: 79
Reputation: 3476
So you have a List<SpecialistInfo>
and each SpecialistInfo
has a List<Specialization>
. You need to reverse map these. Presumably, then, Specialization
and SpecialistInfo
are unique and there exists a many-to-many relation between Specializations
and SpecialistInfo
.
If you're looking for a solution not using the streams API which is thread-safe (compared to the solution of YCF_L)
List<SpecialistInfo> specialists = getSpecialists();
Map<Specialization, List<SpecialistInfo>> specMap = new HashMap<>();
for (SpecialistInfo specInfo : specialists) {
for (Specialization spec : specInfo.getSpecializations()) {
specMap.computeIfAbsent(spec, k -> new ArrayList<>()).add(specInfo);
}
}
Upvotes: 3