Skip to content
Advertisement

Converting a Map into a sorted TreeSet using streams

The code is:

public TreeSet<VehicleTransportation> allVehicleTransportations(){
        
        Set<VehicleTransportation> sortedVehicles = allVehicleTransportation.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue.pollutionLevel , Comparator.reverseOrder()))
                .sorted(Comparator.comparing(Map.Entry::getValue.price))
                .map(Map.Entry::getValue)
                .collect(Collectors.toSet());

        return sortedVehicles;
    }

Where the HashMap is

HashMap<String, VehicleTransportation> allVehicleTransportation = new HashMap<String, VehicleTransportation>();

There are 2 problems I run into using this code. First, for some reason Map.Entry::getValue runs into the error : The target type of this expression must be a functional interface I think the problem here is that the comparator cannot compare between two objects of type VehicleTransportation although pollutionLevel and price are both strings.

Second , I cannot quite figure out how to convert the Set into a TreeSet (maybe use (TreeSet<VehicleTransportation>) ?)

Advertisement

Answer

A treeset is sorted anyway, so I would say the streams you are using to add to the treeset, even if it worked as you intend, the sorted items would be resorted according to their natural ordering, destroying any sort order that was created by the stream.

Instead, you should specify a sort order on the treeset, and then just addAll(VehicleTransportation.values()) and forget about streams! it will be sorted according to the sort order.

If you want to sort using streams, you’ll have to return something other than the treeset (maybe an arrayList) which will not alter the sort order that you have defined.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement