Merge Java threads or reduce duplicate objects

I need to create a unique list of friends from a list that can have duplicates, combining all the duplicate entries into one object
Example . Friends are obtained from different social channels and placed on one big list
 1. Friend - [name: "Johnny Depp", ext: "1970-11-10", source: "FB", fbAttribute: ".."]
 2. Friend - [name: "Christian Bale", ext: "1970-01-01", source: "LI", liAttribute: ".."]
 3. Friend - [name: "Johnny Depp", ext: "1970-11 -10 ", source:" Twitter ", twitterAttribute:" .. "]
 4. Friend - [name:" Johnny Depp ", ext:" 1970-11-10 ", source:" LinkedIn ", liAttribute:" .. "]
 5. Friend - [name:"Christian Bale", dob: "1970-01-01", source: "LI", liAttribute: ".."]

Expected Result
 1. Friend - [name: "Christian Bale", dob: "1970-01-01", liAttribute: "..", fbAttribute: "..", twitterAttribute: ".."]
 2. Friend - [ name: "Johnny Depp", dob: "1970-11-10", liAttribute: "..", fbAttribute: "..", twitterAttribute: ".."]

Question . How can I combine without using an intermediate container? I can easily use an intermediate map and apply a shorthand for each record value.

List<Friend> friends;
Map<String, List<Friend>> uniqueFriendMap
    = friends.stream().groupingBy(Friend::uniqueFunction);
List<Friend> mergedFriends = uniqueFriendMap.entrySet()
    .stream()
    .map(entry -> {
           return entry.getValue()
                .stream()
                .reduce((a,b) -> friendMergeFunction(a,b));
    })
    .filter(mergedPlace -> mergedPlace.isPresent())
    .collect(Collectors.toList());

I like to do this without using the uniqueFriendMap middleware. Any suggestions?

+4
source share
2 answers

groupingBy ( ) , Map . :

Map<String, Friend> uniqueFriendMap = friends.stream()
    .collect(Collectors.groupingBy(Friend::uniqueFunction,
        Collectors.collectingAndThen(
            Collectors.reducing((a,b) -> friendMergeFunction(a,b)), Optional::get)));

. List, Collection:

List<Friend> mergedFriends = new ArrayList<>(uniqueFriendMap.values());

, collect:

List<Friend> mergedFriends = friends.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(Friend::uniqueFunction, Collectors.collectingAndThen(
            Collectors.reducing((a,b) -> friendMergeFunction(a,b)), Optional::get)),
        m -> new ArrayList<>(m.values())));

, . Map, entrySet(), getValue() . values() . input -> { return expression; }, input -> expression . , . , :

Map<String, List<Friend>> uniqueFriendMap
    = friends.stream().collect(Collectors.groupingBy(Friend::uniqueFunction));
List<Friend> mergedFriends = uniqueFriendMap.values().stream()
    .map(group -> group.stream().reduce((a,b) -> friendMergeFunction(a,b)).get())
    .collect(Collectors.toList());

. , Map, . List, , Friend .

+5

Collectors.frequency.

+2

Source: https://habr.com/ru/post/1666196/


All Articles