mro*_*rod 23 java java-8 java-stream
我如何使用Java Streams执行以下操作?
假设我有以下课程:
class Foo {
Bar b;
}
class Bar {
String id;
String date;
}
Run Code Online (Sandbox Code Playgroud)
我有一个List<Foo>,我想将其转换为Map <Foo.b.id, Map<Foo.b.date, Foo>.即:首先按组Foo.b.id,然后按Foo.b.date.
我正在努力采用以下两步法,但第二步甚至没有编译:
Map<String, List<Foo>> groupById =
myList
.stream()
.collect(
Collectors.groupingBy(
foo -> foo.getBar().getId()
)
);
Map<String, Map<String, Foo>> output = groupById.entrySet()
.stream()
.map(
entry -> entry.getKey(),
entry -> entry.getValue()
.stream()
.collect(
Collectors.groupingBy(
bar -> bar.getDate()
)
)
);
Run Code Online (Sandbox Code Playgroud)
提前致谢.
Flo*_*own 40
您可以一次性对数据进行分组,假设只有不同的数据Foo:
Map<String, Map<String, Foo>> map = list.stream()
.collect(Collectors.groupingBy(f -> f.b.id,
Collectors.toMap(f -> f.b.date, Function.identity())));
Run Code Online (Sandbox Code Playgroud)
使用静态导入保存一些字符:
Map<String, Map<String, Foo>> map = list.stream()
.collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));
Run Code Online (Sandbox Code Playgroud)
假设(b.id, b.date)对是不同的。如果是这样,在第二步中,您不需要分组,只需收集到Mapkey 所在位置foo.b.date和 valuefoo本身:
Map<String, Map<String, Foo>> map =
myList.stream()
.collect(Collectors.groupingBy(f -> f.b.id)) // map {Foo.b.id -> List<Foo>}
.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), // id
e -> e.getValue().stream() // stream of foos
.collect(Collectors.toMap(f -> f.b.date,
f -> f))));
Run Code Online (Sandbox Code Playgroud)
或者更简单:
Map<String, Map<String, Foo>> map =
myList.stream()
.collect(Collectors.groupingBy(f -> f.b.id,
Collectors.toMap(f -> f.b.date,
f -> f)));
Run Code Online (Sandbox Code Playgroud)