BAEL-2480 Java Map to String conversion (#6075)
* BAEL-2480 Java Map to String conversion * BAEL-2480 Java Map to String conversion * BAEL-2480 Java Map to String conversion * BAEL-2480 Java Map to String conversion
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.convert;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MapToString {
|
||||
|
||||
public static String convertWithIteration(Map<Integer, ?> map) {
|
||||
StringBuilder mapAsString = new StringBuilder("{");
|
||||
for (Integer key : map.keySet()) {
|
||||
mapAsString.append(key + "=" + map.get(key) + ", ");
|
||||
}
|
||||
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
|
||||
return mapAsString.toString();
|
||||
}
|
||||
|
||||
public static String convertWithStream(Map<Integer, ?> map) {
|
||||
String mapAsString = map.keySet().stream()
|
||||
.map(key -> key + "=" + map.get(key))
|
||||
.collect(Collectors.joining(", ", "{", "}"));
|
||||
return mapAsString;
|
||||
}
|
||||
|
||||
public static String convertWithGuava(Map<Integer, ?> map) {
|
||||
return Joiner.on(",").withKeyValueSeparator("=").join(map);
|
||||
}
|
||||
|
||||
public static String convertWithApache(Map map) {
|
||||
return StringUtils.join(map);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.convert;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StringToMap {
|
||||
|
||||
public static 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;
|
||||
}
|
||||
|
||||
public static Map<String, String> convertWithGuava(String mapAsString) {
|
||||
return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user