'List<String> to Map<String,String> with stream, with String splitting
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];
Solution 1:[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!
- Fix
toMapcollector 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())
));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
