How to search between two Streams in Java 8
You can't iterate Stream
s more than once. So your current code doesn't work (you get an exception like IllegalStateException: Stream already closed
. From the java doc:
A stream should be operated on (invoking an intermediate or terminal stream operation) only once.
A possible solution would be to convert the pendingTransactionStream
into a map where the key is the type of the id
(I use string, because I don't know the keyType):
Actually a
Set
would be better as you don't need thePendingTransaction
for anything else, for an example have a look at @Eran's answer
Map<String, PendingTransaction> pendingTransactionMap = pendingTransactionStream
.collect(PendingTransaction::getId, Function.identity());
And then filter
your processedTransactionStream
, by checking if the id is in the map:
List<ProcessedTransaction> processedTransactionList = processedTransactionStream
.filter(p -> pendingTransactionMap.containsKey(p.getId()))
.collect(Collectors.toList());
Well, you can't consume the pendingTransactionStream
Stream
multiple times. You can transform it to a List
(or even better, a Set
) of transaction IDs to use in the filter
method.
Set<String> pending = pendingTransactionStream.map(PendingTransaction::getTransactionId)
.collect(Collectors.toSet());
List<ProcessedTransaction> processed =
processedTransactionStream.filter(pt -> pending.contains(pt.getTransactionId()))
.collect(Collectors.toList());