Map <String,List <Object >>的Collectors.toMap无法解析

mas*_*720 4 java java-8 java-stream

我有这种代码和平工作正常,需要一个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());
});
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用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));

});
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*per 5

为了重现您的问题,我创建了一个示例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));
Run Code Online (Sandbox Code Playgroud)

并把它变成了与你相似的流

Stream<Map.Entry<Integer, List<Integer>>> results = mapA.entrySet().stream();
Run Code Online (Sandbox Code Playgroud)

您可能已经注意到,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())));
Run Code Online (Sandbox Code Playgroud)

你将不得不更换Comparator.naturalOrder()用Comparator.comparing(Device::getStationTimeStamp).