2016-04-28 84 views
1

如何使用Java Stream Api替換此代碼?Java Stream Api INNER JOIN兩個列表

for (Book book : Books.getAllBooks()) { 
     for (SearchResult searchResult : searchResultList) { 
      if (searchResult.getTableName().replace("attr_", "") .equals(book.getTableName())) { 
      bookList.add(book); 
      } 
     } 
     } 
+1

那你試試? – Tunaki

回答

2
List<Book> bookList = Books.getAllBooks().stream() 
      .filter(e -> searchResultList.stream() 
         .anyMatch(f -> e.getTableName().equals(f.getTableName().replace("attr_", "")))) 
      .collect(Collectors.toList()); 
2

我從C#來了,錯過了在Java的API 8這個功能,所以我寫了我自己。 隨着streamjoin你可以寫

Stream<Book> books = 
join(Books.getAllBooks().stream()) 
.withKey(Book::getTableName) 
.on(searchResultList.stream()) 
.withKey(SearchResult::getTableName) 
.combine((book, searchResult) -> book) 
.asStream() 
0

正是你問什麼,但這裏有一個技巧,如果你使用的番石榴:

List<Book> bookList = new ArrayList<>(Books.getAllBooks()); 
Lists.transform(bookList, Book::getTableName) 
     .retainAll(Lists.transform(searchResultList, r -> r.getTableName().replace("attr_", ""));