Search code examples
javamultimap

Multimap implementation with duplicate keys


I have a function which returns an array list in the following way

[java.lang.String=name, int=parameters, byte=paramOne, java.lang.String=format, byte=paramTwo]

and is stored in a variable like : List<Entry<String, String>> dataTypes

Now I want to make a map that stores the key-value pairs like this list. I have tried to make separate lists of keys and values and I'm trying to use a multimap to map it against each other but it does not work. (I know hashmaps can't store duplicate keys and will just take the last duplicate key with its respective value, that's why I'm trying to use multimaps) This is the code I'm trying:

        List<String> dataTypeValues = new ArrayList<>();
        List<String> dataTypeKeysList = new ArrayList<>();
        String keyString = null;
        String valueString = null;
                            
        for(Entry<String, String> dt : dataTypes) {
            dataTypeKeys.add(dt.getKey());
            keyString = dataTypeKeys.toString();
            
        }
        for(Entry<String, String> dt : dataTypes) {
            dataTypeValues.add(dt.getValue());
            valueString = dataTypeValues.toString();
        }
        Multimap<String, String> multiMap = ArrayListMultimap.create();         
        multiMap.put(keyString, valueString);
        System.out.println(multiMap);
        

And this is the output I'm getting:

{[java.lang.String, int, byte, java.lang.String, byte]=[[name, parameters, paramOne, format, paramTwo]]}    

And this is the output I'm trying to get:

{java.lang.String=[name], int=[parameters], byte=[paramOne,paramTwo], java.lang.String=[format]}

Any advice would be really helpful. Thanks in advance!

EDIT : The answers provided by @User - Upvote don't say Thanks and @Louis Wasserman works perfectly. I accepted the answer from @User - Upvote don't say Thanks because of the discussion. If I could I would accept both these answers. Thank you


Solution

  • You can use groupingBy which is the ideal case for you I think

    Map<String, List<String>> res =
                    dataTypes.stream().collect(Collectors.groupingBy(Map.Entry::getKey,
                                 Collectors.mapping(Map.Entry::getValue, Collectors.toList())));