List在添加.thenComparing后排序时会会显示为Object对象,从而get报错,解决方法如下,换成以下写法即可
finalList.stream()
.sorted(
Comparator.comparing((Map<String, Object> i) -> i.get("product1").toString())
.thenComparing((Map<String, Object> i) -> i.get("product2").toString())
.thenComparing((Map<String, Object> i) -> i.get("product3").toString())
)
.collect(Collectors.toList());
如果product3是Integer,
finalList.stream()
.sorted(
Comparator.comparing((Map<String, Object> i) -> i.get("product1").toString())
.thenComparing((Map<String, Object> i) -> i.get("product2").toString())
.thenComparing((Map<String, Object> i) -> Integer.valueOf(i.get("product3")))
)
.collect(Collectors.toList());
文章讲述了在Java中使用List流进行排序时,由于元素为Object对象导致get方法报错的解决方案,涉及Comparator链式调用和类型转换(如Integer.valueOf())。
1840

被折叠的 条评论
为什么被折叠?



