I have string which I split to hash map
String myStrFromUser = "app0=aaa,aaa,app1=ccc,ddd,app3=ddd,app4=iii,ddd,qqq,www,iii";
private static HashMap<String, List<String>> myMap = = new HashMap<>();
Arrays.stream(myStrFromUser.split("(,(?=[A-Za-z0-9]*=[^A-Za-z0-9]*))"))
.map(String::trim)
.map(s -> s.split("="))
.collect(Collectors.toMap(str -> s[0], str -> str[1].split(",")))
.forEach((key, value) -> myMap.put(key, Arrays.asList(value)) );
The problem is that i like to prevent inserting duplicate values into new ArrayList<>(Arrays.asList(value))
for example :
app0=aaa,aaa
contains duplicates so I like it to be only 1 "aaa" in the ArrayList<>(Arrays.asList(value))
CodePudding user response:
I think this is what you are looking for.
- continue to the
toMap
part as you did - but for the value, simply create a new stream, splitting on the comma and converting to a list using distinct to get rid of duplicates.
- I would suggest a
list
overset
since sets can't be indexed as they are unordered. If that doesn't matter, convert to a set and remove the distinct call. And change the Map target toSet<String>
String myStrFromUser =
"app0=aaa,aaa,app1=ccc,ddd,app3=ddd,app4=iii,ddd,qqq,www,iii";
Map<String, List<String>> myMap = Arrays.stream(myStrFromUser
.split("(,(?=[A-Za-z0-9]*=[^A-Za-z0-9]*))"))
.map(String::trim).map(s -> s.split("="))
.collect(Collectors.toMap(str -> str[0], str -> Arrays
.stream(str[1].split(",")).distinct().collect(Collectors.toList())));
myMap.entrySet().forEach(System.out::println);
Prints
app0=[aaa]
app1=[ccc, ddd]
app4=[iii, ddd, qqq, www]
app3=[ddd]