按键通过流排序的集合

时间:2017-04-19 06:54:38

标签: java java-8 java-stream

我有一个简单的类,有三个值:

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"}

1 个答案:

答案 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());