Java Stram实现Map和字符串之间互相转换| Baeldung

19-01-18 banq
         

假设有数据在Map中:

Map<Integer, String> wordsByKey = new HashMap<>();
wordsByKey.put(1, "one");
wordsByKey.put(2, "two");
wordsByKey.put(3, "three");
wordsByKey.put(4, "four");

希望输出成字符串:

{1=one, 2=two, 3=three, 4=four}

Java Stream实现:

public String convertWithStream(Map<Integer, ?> map) {
    String mapAsString = map.keySet().stream()
      .map(key -> key + "=" + map.get(key))
      .collect(Collectors.joining(", ", "{", "}"));
    return mapAsString;
}

现在,反过来,将上述字符串转换到Map中:

public Map<String, String> convertWithStream(String mapAsString) {
    Map<String, String> map = Arrays.stream(mapAsString.split(","))
      .map(entry -> entry.split("="))
      .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
    return map;
}

展示了Collectors的joining和toMap方法使用。