Java Stram實現Map和字串之間互相轉換| Baeldung

banq發表於2019-01-18

假設有資料在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方法使用。

相關文章