我有一个地图,其中键是一个字符串,值是“计划”对象的列表。 对于每个键,我希望在计划的费用字段中对值(即计划对象列表)进行排序。
例如, IF:计划 1 的费用为 100.20,计划 2 的费用为 400.10,计划 3 的费用为 10.00 AND:在排序之前条目是:["abc", [Plan1 , Plan2, Plan3]] 那么:排序之后条目应该是:["abc", [Plan3, Plan1, Plan2]]
我试过了
map.values()
.forEach(lst -> lst.stream()
.sorted(Comparator.comparingDouble(Plan::getFee)))
.collect(Collectors.toList())
);
但这并没有改变列表的顺序。
有没有办法使用 Streams 来做到这一点?
嘿这是你问题的解决方案,我也在我的机器上测试过。
如果你有一个 getter 方法
getFee()
用于你的计划类中的费用变量。那么下面的一个适合你。
hmap.entrySet().forEach(e->e.getValue().sort(Comparator.comparing(Plan::getFee)));
感谢@tgdavies 提供更简单的方法。这是相同的代码。
hmap.values().forEach(li->li.sort(Comparator.comparing(Plan::getFee)));
即使有时是安全的,在流构造中修改现有状态也不是一个好主意。在这种情况下,我会选择使用 for 循环的标准命令式解决方案。流并不总是最好的解决方案。
这是一个演示。
一些数据和声明
record Plan(double getFee /*other fields as needed */) {
@Override
public String toString() {
return "%.2f".formatted(getFee);
}
}
List<Plan> list1 = new ArrayList<>(List.of(
new Plan(100.20),
new Plan(400.10),
new Plan(10.00)));
List<Plan> list2 = new ArrayList<>(List.of(
new Plan(90.20),
new Plan(30.10),
new Plan(100.00)));
Map<String, List<Plan>> map = Map.of("abc",list1,"def",list2);
迭代、排序、输出
for (List<Plan> list : map.values()) {
list.sort(Comparator.comparing(Plan::getFee));
}
map.entrySet().forEach(System.out::println);
版画
abc=[10.00, 100.20, 400.10]
def=[30.10, 90.20, 100.00]