我有
class Activity {
int id;
ActivityType activityType;
}
class ActivityType {
int id;
}
class Tournament {
int id;
List<Activity> activities;
}
我有一个
List<Tournament> tournaments;
从此我需要
Map<Tournament, Map<ActivityType, Map<Integer, Activity>>>
(Integer
是activityId
)
如何使用Java 8获得它?
答案 0 :(得分:1)
如果我理解正确,Map<Integer, Activity>
始终只包含一个元素。在这种情况下,它看起来更像是toMap
而不是groupingBy
。类似的东西:
Map<Tournament, Map<Activity, Map<Integer, Activity>>> map = tournaments.stream()
.collect(toMap(t -> t,
t -> t.getActivities().stream().collect(toMap(a -> a, a -> map(a)))));
使用此辅助方法:
private static Map<Integer, Activity> map(Activity a) {
Map<Integer, Activity> m = new HashMap<> ();
m.put(a.getId(), a);
return m;
}
答案 1 :(得分:1)
如果您有办法从jdk-9获取Collectors.flatMapping
(我认为它存在于StreamEx
库中),那么它可能如下所示:
Stream.of(new Tournament()).collect(Collectors.groupingBy(Function.identity(),
Collectors.flatMapping(t -> t.getActivities().stream(),
Collectors.groupingBy(Activity::getActivityType,
Collectors.toMap(Activity::getId, Function.identity()))
)));
使用StreamEx ,它可能如下所示:
Stream.of(new Tournament()).collect(Collectors.groupingBy(Function.identity(),
MoreCollectors.flatMapping(t -> t.getActivities().stream(),
Collectors.groupingBy(Activity::getActivityType,
Collectors.toMap(Activity::getId, Function.identity())))));
答案 2 :(得分:0)
这是我能够提出的最好的java8。
Map<Tournament, Map<Activity, Map<Integer, Activity>>> map = tournaments.stream()
.collect(toMap(identity(),
t -> t.getActivities().stream()
.collect(groupingBy(A::getActivityType(),
a -> toMap(A::getId, identity())))));