gpt4 book ai didi

java - 如何将 List 转换为 Map

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:20:15 25 4
gpt4 key购买 nike

如何使用流将列表转换为列表的映射?

我要转换List<Obj>Map<Obj.aProp, List<Obj.otherProp>> ,
不仅List<Obj>Map<Obj.aProp, List<Obj>>

class Author {
String firstName;
String lastName;
// ...
}

class Book {
Author author;
String title;
// ...
}

这是我要转换的列表:

List<Book> bookList = Arrays.asList(
new Book(new Author("first 1", "last 1"), "book 1 - 1"),
new Book(new Author("first 1", "last 1"), "book 1 - 2"),
new Book(new Author("first 2", "last 2"), "book 2 - 1"),
new Book(new Author("first 2", "last 2"), "book 2 - 2")
);

我知道怎么做:

// Map<Author.firstname, List<Book>> map = ...
Map<String, List<Book>> map = bookList.stream()
.collect(Collectors.groupingBy(book -> book.getAuthor().getFirstName()));

但是我能做些什么来获得它:

// Map<Author.firstname, List<Book.title>> map2 = ...
Map<String, List<String>> map2 = new HashMap<String, List<String>>() {
{
put("first 1", new ArrayList<String>() {{
add("book 1 - 1");
add("book 1 - 2");
}});
put("first 2", new ArrayList<String>() {{
add("book 2 - 1");
add("book 2 - 2");
}});
}
};

// Map<Author.firstname, List<Book.title>> map2 = ...
Map<String, Map<String, List<String>> map2 = bookList.stream(). ...
^^^

最佳答案

使用 Collectors.mapping 将每本 Book 映射到相应的标题:

Map<String, List<String>> map = bookList.stream()
.collect(Collectors.groupingBy(book -> book.getAuthor().getFirstName(),
Collectors.mapping(Book::getTitle,Collectors.toList())));

关于java - 如何将 List<Obj1> 转换为 Map<Obj1.prop, List<Obj1.otherProp>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51079072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com