You do not re-check the collection three times.
mostRecentMessageSentDate = messageInfoList .stream() .findFirst().orElse(new MessageInfo()) .getSentDate();
The above checks if there are any elements in the collection, and returns a value depending on this. He does not need to go through the entire collection.
unprocessedMessagesCount = messageInfoList .stream() .filter(messageInfo -> messageInfo.getProcessedDate() == null) .count();
It is necessary to filter out all elements without a process date and read them, so that it goes through the entire collection.
hasAttachment = messageInfoList .stream() .anyMatch(messageInfo -> messageInfo.getAttachmentCount() > 0);
The above must go through the elements until it finds a message with an attachment.
So, of the three threads , only one of them is required to go through the entire collection, in the worst case, you iterate twice (the second and essentially the third thread).
It might be more efficient with a regular For-Each loop, but do you really need this? If your collection contains only a few objects, I would not optimize it.
However, using the traditional For-Each loop, you can combine the last two threads:
int unprocessedMessagesCount = 0; boolean hasAttachment = false; for (MessageInfo messageInfo: messageInfoList) { if (messageInfo.getProcessedDate() == null) { unprocessedMessagesCount++; } if (hasAttachment == false && messageInfo.getAttachmentCount() > 0) { hasAttachment = true; } }
It really is up to you if you think this is a better solution (I also find threads more readable). I see no way to combine the three streams into one, at least in a not more readable way.
Magnilex
source share