0

I have List with Strings:

List<String> cookiesUpdate = Arrays.asList("A=2" , "B=3");
    

I want to convert it to Map:

{
  "A": "2",
  "B": "3"
}

Code:

Map<String, String> cookies = cookiesUpdate.stream()
     .collect(Collectors.toMap(String::toString, String::toString));

How to write those splitters above? If compiler thinks key String is Object.

.split("=")[0];
.split("=")[1];

1 Answer 1

6
  1. Split should be done by "=" (or "\\s*=\\s" to exclude whitespaces around =)

Update Also it is better to provide limit argument to String::split to split at the first occurrence of "=", thanks @AndrewF for suggestion!

  1. Fix toMap collector to use the first element of the array as key and the last as the value; a merge function may be needed if several namesake cookies are possible
Map<String, String> map = cookies.stream()
    .map(ck -> ck.split("\\s*=\\s*", 2)) // Stream<String[]>
    .filter(arr -> arr.length > 1) // ignore invalid cookies
    .collect(Collectors.toMap(arr -> arr[0], arr -> arr[1], (v1, v2) -> v1));

If there are multiple cookies with the same name, it may be worth to collect them into Set<String> thus keeping all unique values. For this, Collectors.groupingBy and Collectors.mapping:

Map<String, Set<String>> map2 = cookies.stream()
    .map(ck -> ck.split("\\s*=\\s*", 2)) // Stream<String[]>
    .filter(arr -> arr.length > 1) // ignore invalid cookies
    .collect(Collectors.groupingBy(
        arr -> arr[0], 
        Collectors.mapping(arr -> arr[1], Collectors.toSet())
    ));
Sign up to request clarification or add additional context in comments.

3 Comments

Consider String.split( /* ... */ , 2) so that any equals signs in the value will not result in an array with length > 2 and truncated value in the final result.
String.split("\\s*=\\s*", 2) will result in a compilation error Cannot make a static reference to the non-static method split(String, int) from the type String. And you don't need , (v1, v2) -> v1.
@saka1029, you're right, it should be ck.split, I fixed that. The merge function may be needed to handle possible duplicates of cookie names to prevent failing after java.lang.IllegalStateException: Duplicate key a (attempted merging values b and c) if the test data are: List<String> cookies = Arrays.asList("a=b", "a=c", "p=qqq");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.