I have a HashMultimap
Multimap<String, String> map = HashMultimap.create();
The data I put into the map is
map.put("cpu", "i9");
map.put("hang", "MSI");
map.put("hang", "DELL");
map.put("hang", "DELL");
map.put("cpu", "i5");
map.put("hang", "HP");
map.put("cpu", "i7");
I have a stream
String joinString = map.entries().stream().map(e -> e.getKey() "=" e.getValue()).collect(Collectors.joining(" OR "));
I need the output to be
(hang=HP OR hang=MSI OR hang=DELL) AND (cpu=i9 OR cpu=i5 OR cpu=i7)
I need an AND in between the keys. How can I do that?
CodePudding user response:
Use the Map view:
String joined = map.asMap()
.entrySet()
.stream()
.map(e -> e.getValue()
.stream()
.map(v -> e.getKey() "=" v)
.collect(Collectors.joining(" OR ", "(", ")")))
.collect(Collectors.joining(" AND "));
CodePudding user response:
Of course schmosel beat me, but here a slightly different api/usage:
String joined = map.keySet() // keySet() instead of asMap()
.stream().map(k
-> String.format( // string.format instead of concatenation ;)
"(%s)",
map.get(k).stream() // map.get(k) instead of e.getValue()
.map(v
-> String.format("%s=%s", k, v))
.collect(Collectors.joining(" OR "))
)
).collect(Collectors.joining(" AND "));