我有一个HashMultimap
Multimap<String, String> map = HashMultimap.create();
我在地图上放的数据是
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");我有一条小溪
String joinString = map.entries().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(" OR "));我需要输出
(hang=HP或hang=MSI或hang=DELL) 和 (cpu=i9或cpu=i5或cpu=i7)
我需要一个AND在钥匙之间。我怎么能这么做?
发布于 2021-12-31 02:55:51
使用Map视图:
String joined = map.asMap()
.entrySet()
.stream()
.map(e -> e.getValue()
.stream()
.map(v -> e.getKey() + "=" + v)
.collect(Collectors.joining(" OR ", "(", ")")))
.collect(Collectors.joining(" AND "));发布于 2021-12-31 03:23:58
当然,schmosel击败了我,但是这里的api/用法略有不同:
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 "));https://stackoverflow.com/questions/70538376
复制相似问题