Collectors.toMap of Map <String, List <Object> cannot resolve
This code world works fine for me, which takes Map<String, List<Device>>sorting time and returns the same data structure:
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());
});
Now I tried to use Collectors.toMapand did not succeed:
Map<String, List<Device>> sortedMap = results.forEach(e -> {
e.getValue().stream()
.sorted(Comparator.comparing(Device::getStationTimeStamp))
.collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new));
});
Part .collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new));is what I tried and it is not quite right, what did I do wrong?
+4
1 answer
To reproduce your problem, I created a Map example
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));
and turned it into a stream similar to yours
Stream<Map.Entry<Integer, List<Integer>>> results = mapA.entrySet().stream();
As you may have noticed, lists in mapA are not sorted.
To get Map<Integer,List<Integer>>with sorting List, you can do the following
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).
+5