Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: How to convert String to Map<String,String>?

I have a Map:

Map<String, String> utilMap = new HashMap();
utilMap.put("1","1");
utilMap.put("2","2");
utilMap.put("3","3");
utilMap.put("4","4");

I converted it to a String:

String utilMapString = utilMap
                .entrySet()
                .stream()
                .map(e -> e.toString()).collect(Collectors.joining(","));
Out put: 1=1,2=2,3=3,4=4,5=5

How to convert utilMapString to Map in Java8? Who can help me with?

like image 435
Phuong Avatar asked Oct 08 '18 04:10

Phuong


2 Answers

Here is another option which streams a list of 1=1 etc. terms into a map.

String input = "1=1,2=2,3=3,4=4,5=5";
Map<String, String> map = Arrays.asList(input.split(",")).stream().collect(
             Collectors.toMap(x -> x.replaceAll("=\\d+$", ""),
                 x -> x.replaceAll("^\\d+=", "")));
System.out.println(Collections.singletonList(map));

[{1=1, 2=2, 3=3, 4=4, 5=5}]
like image 44
Tim Biegeleisen Avatar answered Sep 28 '22 06:09

Tim Biegeleisen


Split the string by , to get individual map entries. Then split them by = to get the key and the value.

Map<String, String> reconstructedUtilMap = Arrays.stream(utilMapString.split(","))
            .map(s -> s.split("="))
            .collect(Collectors.toMap(s -> s[0], s -> s[1]));

Note: As pointed out by Andreas@ in the comments, this is not a reliable way to convert between a map and a string

EDIT: Thanks to Holger for this suggestion.

Use s.split("=", 2) to ensure that the array is never larger than two elements. This will be useful to not lose the contents (when the value has =)

Example: when the input string is "a=1,b=2,c=3=44=5555" you will get {a=1, b=2, c=3=44=5555}

Earlier (just using s.split("=")) will give {a=1, b=2, c=3}

like image 124
user7 Avatar answered Sep 28 '22 06:09

user7