简体   繁体   中英

Map fields of a List to another List

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());
       }
  });
});

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());

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM