Java 8 Collectors toMap
Java 8 Collectors toMap
在使用Java stream的时候,会有需要将stream转换为Map的需求。
数据结构
下面的例子都会以图书信息作为实体。
public class Book {
private String name;
private Year releaseYear;
private String isbn;
// getters and setters
}
准备数据
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("计算机程序的构造和解释", Year.of(2004), "9787111135104"));
bookList.add(new Book("算法导论", Year.of(2012), "9787111407010"));
bookList.add(new Book("计算机组成原理", Year.of(2017), "9787111558071"));
bookList.add(new Book("编译原理", Year.of(2008), "9787111251217"));
bookList.add(new Book("C程序设计语言(第2版·新版)", Year.of(2004), "9787111128069"));
toMaps
以ISBN作为key,以book作为value
bookList.stream().collect(Collectors.toMap(Book::getIsbn, Function.identity()))
以ISBN作为Key, 以书名作为value
bookList.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName));
以年份为Key,统一年的书构建为一个list作为值
bookList.stream().collect(Collectors.toMap(
Book::getReleaseYear,
book -> {
List<Book> books = new ArrayList<>();
books.add(book)
return books;
},
(prev, curr) -> {
prev.addAll(curr);
return prev;
}
))