1

In a kind of chat with a chatbot that I'm implementing, I have a List of Conversation and every Conversation has a List of Messages. I want to add those conversations that its last message is not a chatbot message and is not viewed by the user to a List of Conversations. To do that I'm coding it as bellow:

List<ConversationDto> conversationsToBeSent = new ArrayList<>();

for (ConversationDto conversation : super.allConversations) {
    if (conversation.getMessages() != null) {
        if (conversation.getMessages().get(0).getMessageType().getId() != MessageTypeEnum.CHATBOT.getValue()
                && conversation.getMessages().get(0).getToViewedAt() == null) {
            conversationsToBeSent.add(conversation);
        }
    }

}

This is working. The question is how can I code that using Lambda and stream instead of for each.

1
  • 1
    Hi! Please show us what you've tried so far, so that we can see what you need help with Commented Dec 2, 2020 at 12:50

2 Answers 2

5

Your problem is a classical "Filter a collection" task. This is what the Stream.filter() method does.

A code block:

List<Item> newList = new ArrayList<>();
for (Item item : collection) {
    if (predicate(item)) {
        newList.add(item);
    }
}

can generally be converted to:

List<Item> newList = 
    collection
        .stream()
        .filter(item -> predicate(item))
        .collect(Collectors.toList());

In your case, the code transforms as follows. Note the comments in the following code block for explanations:

List<ConversationDto> conversationsToBeSent = super.allConversations // Start with the original list
    .stream() // Get a stream of list items
    .filter(conversation -> // Filter the list items
        conversation.getMessages() != null
        && !conversation.getMessages().isEmpty() // YOU PROBABLY WANT THIS CHECK AS WELL!
        && conversation.getMessages().get(0).getMessageType().getId() != MessageTypeEnum.CHATBOT.getValue()
        && conversation.getMessages().get(0).getToViewedAt() == null
    )
    .collect(Collectors.toList()); // Collect the stream items to a new list
Sign up to request clarification or add additional context in comments.

Comments

3

To use stream on a list, just do super.allConversations.stream() Then if you want to select only some elements, you can use the filter method like in the code below:

super.allConversations.stream().filter(
  conversation ->
    conversion != null && 
    conversation.getMessages().get(0).getMessageType().getId() != MessageTypeEnum.CHATBOT.getValue() &&
    conversation.getMessages().get(0).getToViewedAt() == null
);

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.