java8 Collector.tomap具有合并功能,在复制密钥时将值放入收集器
假设下面有代码,如何才能返回带有重复键的列表java8 Collector.tomap具有合并功能,在复制密钥时将值放入收集器,java,collections,Java,Collections,假设下面有代码,如何才能返回带有重复键的列表 private List<Book> getDummyBooks() { List<Book> books = new ArrayList<>(); books.add(new Book("The Fellowship of the Ring", 1954, "0395489318")); books.add(new Book(
private List<Book> getDummyBooks() {
List<Book> books = new ArrayList<>();
books.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
books.add(new Book("The Two Towers", 1954, "0345339711"));
books.add(new Book("The Return of the King", 1955, "0618129111"));
return books;
}
// first object is returned when duplicated key
private Map<Integer, Book> listToMapWithMerge(List<Book> books) {
return books.stream().collect(
Collectors.toMap(
Book::getReleaseYear
, Function.identity()
, (exising,replacement) -> exising));
}
private Map<Integer, List<Book> > listToMapWithMerge(List<Book> books) {
return books.stream().collect(
Collectors.toMap(
Book::getReleaseYear
, new ArrayList<>Function.identity()
, ...));
}
private List getDummyBooks(){
List books=new ArrayList();
图书。添加(新书(“魔戒团契”,1954年,“0395489318”);
新增(新书(“双塔”,1954年,“0345339711”);
新增(新书《国王归来》,1955年,0618129111);
还书;
}
//复制密钥时返回第一个对象
私有地图列表ToMapWithMerge(图书列表){
return books.stream().collect(
汤姆(
书籍::getReleaseYear
,Function.identity()
,(退出,替换)->退出);
}
如果要返回具有重复键的列表,该怎么办
private List<Book> getDummyBooks() {
List<Book> books = new ArrayList<>();
books.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
books.add(new Book("The Two Towers", 1954, "0345339711"));
books.add(new Book("The Return of the King", 1955, "0618129111"));
return books;
}
// first object is returned when duplicated key
private Map<Integer, Book> listToMapWithMerge(List<Book> books) {
return books.stream().collect(
Collectors.toMap(
Book::getReleaseYear
, Function.identity()
, (exising,replacement) -> exising));
}
private Map<Integer, List<Book> > listToMapWithMerge(List<Book> books) {
return books.stream().collect(
Collectors.toMap(
Book::getReleaseYear
, new ArrayList<>Function.identity()
, ...));
}
private Map listomapwithmerge(图书列表){
return books.stream().collect(
汤姆(
书籍::getReleaseYear
,新的ArrayListFunction.identity()
, ...));
}
使用收集器。分组方式
:
private Map listomapwithmerge(图书列表){
return books.stream().collect(
Collectors.groupingBy(Book::getReleaseYear));
}