我有一个简单的类,有三个值:
class Book{
private String title;
private String author;
private double price;
}
title
是唯一的(总是)。系统中列出了所选标题(List<String>
)和每个Book
的列表。我希望从标题列表中获取所有Book
密钥。我的代码是:
List<Book> allBooks = getAllBooks();
List<String> selectedTitles = getSelectedTitles();
List<Book> selectedBooks = allBooks.stream().
filter(x -> selectedTitles.contains(x.getTitle())).
collect(Collectors.toList());
它有效但选择的书籍是allBook
selectedTitles
的{{1}}。例如:
allBooks(only title) = {"A","B","C","D"}
selectedTitles = {"B","A","D"}
selectedBooks(only title) = {"A","B","D"}
如何通过stream()
通过selectedTitles
订购?(对于此示例,它应该是{"B","D","A"}
?
答案 0 :(得分:7)
不要排序,只需查看已选择的书籍:
List<Book> allBooks = getAllBooks();
List<String> selectedTitles = getSelectedTitles();
Map<String,Book> titleToBook = allBooks.stream()
.collect(Collectors.toMap(Book::getTitle, Function.identity()));
List<Book> selectedBooks = selectedTitles.stream()
.map(titleToBook::get).filter(Objects::nonNull)
.collect(Collectors.toList());