How to write the merge function for Collectors.toMap()

2020-02-26 java collections java-stream

Here UserMst is the object and users is the List from which I get LoginId && TenantId.

LinkedHashMap<String, String> Tmap = users.stream().collect(Collectors.toMap(
                    UserMst::getLoginId, UserMst::getTenantId,
                        (x, y)-> ((x=="1") ? "Rocks" : (x=="2")
                                           ? "Mocks" : (x=="3")
                                           ? "Docs"  : (x=="4")
                                           ? "Pocks" : "")
                                   + " ,  " + ( (y=="1") ? "Rocks": (y=="2")
                                                         ? "Mocks": (y=="3")
                                                         ? "Docs" : (y=="4")
                                                         ? "Pocks": ""),
                        LinkedHashMap::new));


///////////////////

LinkedHashMap<String, String> Tmap =
    users.stream().collect(
        Collectors.toMap( UserMst::getLoginId, UserMst::getTenantId,
        (x, y)-> x + ", " + y, LinkedHashMap::new)); 

```

It gives output as answer:: rajat=1,2,3 dave=1,2 milind=2,3
I just need these 1,2,3,4 replaced with strings

Answers

The 3rd argument to Collectors.toMap() is the merge function, which is a function that gets two values of the Map, and returns a "merged" value. This is used to merge multiple values that correspond with the same key.

It is not suitable to transform the values of your map from "1","2","3",... to other Strings.

To replace the numeric values with Strings, you can perform the transformation in the value mapper:

LinkedHashMap<String, String> Tmap = 
    users.stream()
         .collect(Collectors.toMap(UserMst::getLoginId,
                                   u -> convert(u.getTenantId()),
                                   (x, y)-> x + ", " + y,
                                   LinkedHashMap::new)); 

where convert is a method that accepts a String such as "1" and returns the corresponding String.

For example:

public static convert (String x)
{
    return x.equals("1")?"Rocks":x.equals("2")?"Mocks":x.equals("3")?"Docs":x.equals("4")?"Pocks":"";
}

Or you can add to UserMst class a method that returns the String corresponding with the getTenantID() of that instance, and then simply write:

LinkedHashMap<String, String> Tmap = 
    users.stream()
         .collect(Collectors.toMap(UserMst::getLoginId,
                                   UserMst::getTenantString,
                                   (x, y)-> x + ", " + y,
                                   LinkedHashMap::new)); 

Related