你能帮我找出更好/更干净的解决方案吗?下一种情况:以字符串的格式收集Web元素属性:
animation-delay:0s;animation-direction:normal;animation-duration:0s;目标:创建属性及其值的Map。注意:在属性中值重复是possile,例如'none‘。
当前可行的解决方案:从字符串到表单列表-
List<String> list = Arrays.stream(attributes.split(";")).collect(Collectors.toList());
Map<String, String> map = new HashMap<>();
for (String s : list) map.put(s.split(":")[0], s.split(":")[1]);但可能只用一个流就能得到相同的结果,但重复流就有问题了。不是在Map中不允许的键中,而是在收集操作期间仍然作为键的重复值。例如,width和height的值都可以是100px,这会在流中产生异常。下面的解决方案-不起作用...
Arrays.stream(attributes.split(";"))
.distinct()
.map(entry -> entry.split(":"))
.collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));提前感谢您的帮助!
发布于 2021-03-05 04:09:57
这应该通过映射到表示键-值对的某个对象来完成,在最简单的情况下,它可以是一个字符串列表/数组,然后使用Collectors.toMap将这些对收集到Map中
String attributes = "width:100px;height:100px;animation-delay:0s;"
+ "animation-direction:normal;animation-duration:0s;font-family:Arial;"
+ "font-family:Helvetica;font-family:sans-serif";
Map<String, String> map = Arrays.stream(attributes.split(";"))
.map(pair -> pair.split(":"))
.filter(arr -> arr.length > 1) // keep only key:value pairs
.collect(Collectors.toMap(
arr -> arr[0],
arr -> arr[1],
(v1, v2) -> String.join(", ", v1, v2) // merge values if needed
, LinkedHashMap::new // optional argument to keep insertion order
));
map.forEach((k, v) -> System.out.printf("%s: %s%n", k, v));输出:
width: 100px
height: 100px
animation-delay: 0s
animation-direction: normal
animation-duration: 0s
font-family: Arial, Helvetica, sans-serif也可以使用Collectors.groupingBy + Collectors.mapping + Collectors.joining来采集地图
Map<String, String> map = Arrays.stream(attributes.split(";"))
.map(pair -> pair.split(":"))
.filter(arr -> arr.length > 1) // keep only key:value pairs
.collect(Collectors.groupingBy(
arr -> arr[0],
TreeMap::new, // optional, sort by keys
Collectors.mapping(arr -> arr[1], Collectors.joining(", "))
));输出:
animation-delay: 0s
animation-direction: normal
animation-duration: 0s
font-family: Arial, Helvetica, sans-serif
height: 100px
width: 100pxhttps://stackoverflow.com/questions/66481931
复制相似问题