gpt4 book ai didi

java - Map> 的 Collectors.toMap 无法解析

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:57 25 4
gpt4 key购买 nike

我的代码运行良好,需要 Map<String, List<Device>>并对时间进行排序并返回相同的数据结构:

Stream<Map.Entry<String, List<Device>>> results = device.getDeviceMapList().entrySet().stream();

Map<String, List<Device>> sortedMap = new HashMap<String, List<Device>>();

results.forEach(e -> {
e.getValue().sort(Comparator.comparing(Device::getStationTimeStamp));
sortedMap.put(e.getKey(), e.getValue());
});

现在我尝试使用 Collectors.toMap并没有成功:

Map<String, List<Device>> sortedMap = results.forEach(e -> {
e.getValue().stream()
.sorted(Comparator.comparing(Device::getStationTimeStamp))
.collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new));

});

部分.collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new));是我试过的但不完全正确,我做错了什么?

最佳答案

为了重现您的问题,我创建了一个示例 map

Map<Integer, List<Integer>> mapA = new HashMap<>();
mapA.put(1, Arrays.asList(1,2,3,4,5,8,7,6,9));
mapA.put(2, Arrays.asList(1,2,3,5,4,6,7,8,9));
mapA.put(3, Arrays.asList(2,3,1,4,5,6,7,8,9));
mapA.put(4, Arrays.asList(1,2,8,4,6,5,7,3,9));
mapA.put(5, Arrays.asList(9,2,3,4,5,6,7,8,1));

然后把它变成一个类似于你的 Stream

Stream<Map.Entry<Integer, List<Integer>>> results = mapA.entrySet().stream();

您可能已经注意到,mapA 中的列表未排序。

获取Map<Integer,List<Integer>>List排序后,您可以执行以下操作

Map<Integer,List<Integer>> sortedMap =          
results.collect(Collectors.toMap(s -> s.getKey(),
s -> s.getValue().stream()
.sorted(Comparator.naturalOrder()).collect(Collectors.toList())));

您必须更换 Comparator.naturalOrder()Comparator.comparing(Device::getStationTimeStamp) .

关于java - Map<String, List<Object>> 的 Collectors.toMap 无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43408036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com