Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the key in Collectors.toMap merge function?

When a duplicate key entry is found during Collectors.toMap(), the merge function (o1, o2) is called.

Question: how can I get the key that caused the duplication?

String keyvalp = "test=one\ntest2=two\ntest2=three";

Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .collect(Collectors.toMap(
        split -> split[0],
        split -> split[1],
        (o1, o2) -> {
            //TODO how to access the key that caused the duplicate? o1 and o2 are the values only
            //split[0]; //which is the key, cannot be accessed here
        },
    HashMap::new));

Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.

like image 749
membersound Avatar asked Jun 07 '17 08:06

membersound


People also ask

What is Merge function in collectors toMap?

Collectors.toMap() with Mapper and Merge FunctionsIt's input are two values that is the two values for which keyMapper returned the same key, and merges those two values into a single one.

How do you collect a map?

Method 1: Using Collectors.toMap() Function The Collectors. toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key.


1 Answers

You need to use a custom collector or use a different approach.

Map<String, String> map = new Hashmap<>();
Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .forEach(arr -> map.merge(arr[0], arr[1], (o1, o2) -> /* use arr[0]));

Writing a custom collector is rather more complicated. You need a TriConsumer (key and two values) is similar which is not in the JDK which is why I am pretty sure there is no built in function which uses. ;)

like image 116
Peter Lawrey Avatar answered Oct 21 '22 00:10

Peter Lawrey