3

I am new to Java 8, I have 2 List of Chat, i wish to set some fields in List A from List B if their id is match

Chat:

public class Chat {

    private String id;

    private Status status;

    private Rating rating;

    //Setters and getters
}

I can do it by using nested loop, but not sure how to do it in java 8:

List<Chat> listA = getDataForA();
List<Chat> listB = getDataForB();

listA .forEach(a -> {
   listB.forEach(b-> {
       if (b.getId().equals(a.getId())) {
            a.setRating(b.getRating());
            a.setStatus(b.getStatus());
       }
  });
});

2 Answers 2

2

can you try this stream, from listA stream we are setting rating and status only if listA and listB ids are matching

    listA.stream()
            .flatMap(a -> listB.stream().filter(b -> b.getId().equals(a.getId())).map(b -> {
                a.setRating(b.getRating());
                a.setStatus(b.getStatus());
                return a;
            }))
            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

why is there a listA.stream().filter inside the flatMap? shouldn't it be listB.stream().filter
2

I would give another approach than simple two loops: group given lists by id and then loop once over all ids:

public static void main(String... args) {
    List<Chat> listA = getDataForA();
    List<Chat> listB = getDataForB();

    Map<String, Chat> mapA = groupById(listA);
    Map<String, Chat> mapB = groupById(listB);

    mapA.entrySet().stream()
        .filter(entry -> mapB.containsKey(entry.getKey()))
        .forEach(entry -> {
            Chat a = entry.getValue();
            Chat b = mapB.get(entry.getKey());
            a.setRating(b.getRating());
            a.setStatus(b.getStatus());
        });
}

private static Map<String, Chat> groupById(Collection<Chat> data) {
    return Optional.ofNullable(data).orElse(Collections.emptyList()).stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
}

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.