Home > Blockchain >  How can I use .collect(Collectors.joining) to convert Map into String
How can I use .collect(Collectors.joining) to convert Map into String

Time:01-04

I have my method that should return String with values from a map. But the problem is that the output of the code below is

Some Word Example

Instead of

Some - 2, Word - 6, Example - 4

public static void main(String[] args) {
        Map<String, Integer> myMap = new HashMap<>();
        myMap.put("Some", 2);
        myMap.put("Example", 4);
        myMap.put("Word", 6);

        System.out.println(countWords(myMap));
    }

        public static String countWords(Map<String, Integer> stringIntegerHashMap) {
        String result = stringIntegerHashMap.entrySet().stream()
                .map(e -> e.getKey())
                .collect(Collectors.joining("\r\n"));
        return result;
    }

CodePudding user response:

Collectors.joining(...) is only responsible to join the Stream-elements with a delimiter. In the given case, however, we have to first map the Stream-emements, i.e. the Map.Entrys, in "the correct format", i.e. "<key> - <value>". For this, we modify the function used by Stream::map:

public static String countWords(Map<String, Integer> stringIntegerHashMap) {
  return stringIntegerHashMap.entrySet().stream()
      .map(entry -> entry.getKey()    " - "   entry.getValue())
      .collect(Collectors.joining("\r\n"));
}

Ideone demo

CodePudding user response:

For now in map you keep only the key, you need to concatenate the key with the value

public static String countWords(Map<String, Integer> stringIntegerHashMap) {
    return stringIntegerHashMap.entrySet().stream()
            .map(e -> e.getKey()   " - "   e.getValue())
            .collect(Collectors.joining("\r\n"));
}
Some-2
Word-6
Example-4
  •  Tags:  
  • Related