我正在尝试对包含嵌套键列表的对象列表进行分组,数据结构如下所示:
class BookInformation {
String accountId;
String bookName;
String bookId;
List<Info> infos;
}
class Info {
String type;
String detail;
}
class GroupedInformation {
String accountId;
Info info;
List<String> bookNames;
}
所以说如果输入是 BookInformation 列表,并按帐户和信息分组在一起,输出是 GroupedInformation 列表,我正在尝试使用
List<GroupedInformation> groupBy(List<BookInformation> toGroup) {
return toGroup.stream.collect(groupingBy(BookInformation::getAccountId), Collectors.??);
}
虽然不确定如何扁平化 List<List> 并按信息再次分组以获得 bookName 的列表,但不引入一些新的数据结构,如 Map<Info, List> 等。有什么想法吗?
为此添加了一个测试:
void test() {
List<BookInformation> toGroup = List.of(
new BookInformation("account1", "bookName1", "book1", List.of(new Info("info1", ""), new Info("info2", ""))),
new BookInformation("account1","bookName2", "book2", List.of(new Info("info2", ""), new Info("info3", ""))),
new BookInformation("account2","bookName3", "book3", List.of(new Info("info3", ""), new Info("info4", "")))
);
List<GroupedInformation> grouped = groupBy(toGroup);
assertThat(grouped).containsExactlyInAnyOrder(
new GroupedInformation("account1", new Info("info1",""), List.of("bookName1")),
new GroupedInformation("account1", new Info("info2",""), List.of("bookName1", "bookName2")),
new GroupedInformation("account1", new Info("info3",""), List.of("bookName2")),
new GroupedInformation("account2", new Info("info3",""), List.of("bookName3")),
new GroupedInformation("account2", new Info("info4",""), List.of("bookName3"))
);
}