0

I am currently having some issues in trying to sort a Map<String, IncreaseDetails>, where IncreaseDetails is simply a custom data structure holding a few fields.

So far I have understood fairly clearly that using a TreeMap is heavily discouraged as a TreeMap should be sorted by the KeySet rather than the actual values.

I have therefore tried to switch to both HashMap and LinkedHashMap but simply calling

Collections.sort(map,comparator) doesn't seem to do the trick. Since Java 8 I was planning on trying to use the Stream API, but I don't really know it too well.

So far my comparator looks like this:

import java.util.Comparator;
import java.util.Map;

public class CompTool implements Comparator<Float> {

    Map<String, IncreaseDetails> unsortedMap;

    public CompTool(Map<String, IncreaseDetails> unsortedMap)
    {
        this.unsortedMap = unsortedMap;
    }

    public int compare(Float countryOne, Float countryTwo)
    {
        Float countryOneValue = unsortedMap.get(countryOne).getRealIncrease();
        Float countryTwoValue = unsortedMap.get(countryTwo).getRealIncrease();
        return countryTwoValue.compareTo(countryOneValue);
    }

}

Any suggestion would be very much welcome, as I have found a lot of similar questions or videos but none too useful for my current situation.

1 Answer 1

1

Your question is somewhat unclear. I assume that you want to sort the unsortedMap entries by the value stored in getRealIncrease in reversed order. This can be done by creating the stream of original map entries, sorting and collecting the result into the LinkedHashMap, which preserves insertion order:

Map<String, IncreaseDetails> sortedMap = unsortedMap.entrySet()
           .stream()
           .sorted(Map.Entry.comparingByValue(
                (Comparator.comparing(IncreaseDetails::getRealIncrease).reversed())))
           .collect(Collectors.toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue,
                (a, b) -> a,
                LinkedHashMap::new));
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if the question wasn't too clear. But anyway, yes that is what I was looking for. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.