使用流将实体结构映射到地图的地图
Map entity structure to map of maps using streams
我有实体:
public class Library {
String name;
Set<Book> books;
}
public class Book {
String isbn;
String title;
}
现在我需要一个
Map<String, Map<String, Book>> mapByLibraryNameAndIsbn;
其中第一个 Map
的键是 Library
的名称,第二个 Map
的键是 Book
.[=19 的 isbn =]
为此,我想使用 java 流和一些收集器。我尝试使用 groupingBy 和 toMap,但都成功了。
更新 1:
到目前为止我试过了
Map<String, List<Book>> libraryList.stream().collect(groupingBy(l -> l.getName(), toList()));
但我刚得到 Map
个 List
s。
有什么想法吗? TIA!
由于您从 List<Library>
开始,您可能希望将 Collectors.toMap()
与 2 个映射函数结合使用:
- 一个库 -> 键的字符串映射器 (returns
name
)
- 一个库 -> 值的地图映射器。
对于第二个映射器,您可能想要流式传输 Set
本书,将它们收集到类似于 'outer' 映射的 Map
中,再次使用 2(不同)映射函数:
- 一本书 -> 键的字符串映射器 (returns
isbn
)
- 值(returns 书籍本身)的标识映射器。
所以像这样:
List<Library> libs;
// populate the libraries
Map<String,Map<String,Book>> map = libs.
stream().
collect(Collectors.toMap(l -> l.name, l -> {
return l.books.
stream().
collect(Collectors.toMap(b -> b.isbn, Function.identity()));
}));
列出库;
使用方法引用和静态导入:
import static java.util.stream.Collectors.toMap;
Map<String, Map<String, Book>> map = libs.stream().collect(
toMap(Library::getName,
l -> l.getBooks().stream().collect(
toMap(Book::getIsbn, b -> b))));
我有实体:
public class Library {
String name;
Set<Book> books;
}
public class Book {
String isbn;
String title;
}
现在我需要一个
Map<String, Map<String, Book>> mapByLibraryNameAndIsbn;
其中第一个 Map
的键是 Library
的名称,第二个 Map
的键是 Book
.[=19 的 isbn =]
为此,我想使用 java 流和一些收集器。我尝试使用 groupingBy 和 toMap,但都成功了。
更新 1:
到目前为止我试过了
Map<String, List<Book>> libraryList.stream().collect(groupingBy(l -> l.getName(), toList()));
但我刚得到 Map
个 List
s。
有什么想法吗? TIA!
由于您从 List<Library>
开始,您可能希望将 Collectors.toMap()
与 2 个映射函数结合使用:
- 一个库 -> 键的字符串映射器 (returns
name
) - 一个库 -> 值的地图映射器。
对于第二个映射器,您可能想要流式传输 Set
本书,将它们收集到类似于 'outer' 映射的 Map
中,再次使用 2(不同)映射函数:
- 一本书 -> 键的字符串映射器 (returns
isbn
) - 值(returns 书籍本身)的标识映射器。
所以像这样:
List<Library> libs;
// populate the libraries
Map<String,Map<String,Book>> map = libs.
stream().
collect(Collectors.toMap(l -> l.name, l -> {
return l.books.
stream().
collect(Collectors.toMap(b -> b.isbn, Function.identity()));
}));
列出库;
使用方法引用和静态导入:
import static java.util.stream.Collectors.toMap;
Map<String, Map<String, Book>> map = libs.stream().collect(
toMap(Library::getName,
l -> l.getBooks().stream().collect(
toMap(Book::getIsbn, b -> b))));