0

Some time ago this question was asked:

Input String: utilMapString = "1=1,2=2,3=3,4=4,5=5"

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

If I change the input to "101|Google,102|Amazon" and perform same transformation, code throws IllegalStateException: Duplicate key

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

Can somebody please explain the exact difference between the two set of operation.

Aman Bharti
  • 17
  • 1
  • 7

1 Answers1

1

You need to escape the pipe character in your second split() call. Like this:

Map<String, String> reconstructedUtilMap = Arrays.stream("101|Google,102|Amazon" .split(","))
                .map(s -> s.split("\\|"))
                .collect(Collectors.toMap(s -> s[0], s -> s[1]));
Madlemon
  • 321
  • 1
  • 9