Peter Jacobsen
Peter Jacobsen

Reputation: 677

Collectors.toMap of Map<String, List<Object>> are not able to resolve

I have this peace of code working fine, that takes a Map<String, List<Device>> and sort time and return the same datastructure:

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.toMap and did not successes:

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

});

The part .collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new)); is what I tried and it is not fully correct, what I have done wrong?

Upvotes: 4

Views: 1149

Answers (1)

Robin Topper
Robin Topper

Reputation: 2345

To reproduce your problem I have created an example 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));

and turned this into a Stream similar to yours

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

As you may have noticed, the Lists in mapA are not sorted.

To get a Map<Integer,List<Integer>> with the List sorted, 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())));

You will have to replace the Comparator.naturalOrder() with Comparator.comparing(Device::getStationTimeStamp).

Upvotes: 5

Related Questions