11

How to replace this code with using Java Stream Api?

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

4 Answers 4

15
List<Book> bookList = Books.getAllBooks().stream()
            .filter(e -> searchResultList.stream()
                         .anyMatch(f -> e.getTableName().equals(f.getTableName().replace("attr_", ""))))
            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

8

I came from C# and missed that feature in Java 8 API, so I wrote my own. With streamjoin you can write

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

Comments

2

Not exactly what you asked for, but here's another trick if you're using Guava:

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

Comments

2

In my opinions, your example is a particular case of join operation, because your result set doesn't take any column of SearchResult. For most people going into this question like me, the general join operation with Java Stream is what they want. And here is my solution :

  • step 1, flatMap with judging whether the result should be null or not
  • step 2, filter the stream in step 1 by nonNull

It works fine, although it's not so elegant, which seems like u implement a join operation yourself--

The pseudocode may like :

//init the two list
List l1 = ...;
List l2 = ...;

//join operation
res = l1.stream().flatMap(
    _item1 -> l2.stream().map(_item2 -> (_item1.join_key == _item2.join_key)?
         ([take the needed columns in item1 and item2]) : null
    )
).filter(Object::nonNull);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.