2

So I'm a newbie and I am struggling a lot with maps. So I have a map and I want to order it by keys in ascending order. But I can't seem to find any solution to that. Thanks for the help!

 LinkedHashMap<String, String> resulting= new LinkedHashMap<>();
 resulting=resulting.entrySet().stream().sorted((a,b)->{
        String first=a.getKey();
        String second=b.getKey();
        return first.compareTo(second)
    });
4
  • 1
    You can get sorted map by TreeMap<String, String> sorted = new TreeMap<>(resulting);. Commented Aug 11, 2017 at 9:07
  • Have a look into stackoverflow.com/a/39533189/7403180 Commented Aug 11, 2017 at 9:15
  • @sForSujit thanks a lot..that seems to work(I did see it before asking the question), but would you mind explaininge how does it work? I Really dont understand how he sorts it? Commented Aug 11, 2017 at 9:39
  • I appreciate the quick comeback. Feel free to practice upvoting now that you reached that level ;-) Commented Aug 11, 2017 at 18:29

1 Answer 1

10

A LinkedHashMaP is ordered based on the insertion order. If you want that the natural order of a LinkedHashMap reflects a sort criteria of some objects, then you first have to establish that order on these objects, before then adding the objects in that order to a fresh LinkedHashMap instance.

In other words: you can't change the order on an existing LinkedHashMap - because the order was fixed when you added the elements to that map initially! Or to be precise: you could only do that by extending the LinkedHashMap class and changing its behavior to break its contract. But that doesn't make sense. You are simply using the wrong data structure to implement your requirement.

If you want a Map that re-orders based on a sorting criteria, you should be looking into a TreeMap for example!

Long story short: you have to differentiate between "order based on insertion order" and "order as result of sorting criteria". You want the later, and LinkedHashMap is the wrong kind of map for that.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your quick and detailed response! I did do it with TreeMap, which would (and it )works in this case. But my problem is that I can't seem to understand how to sort any type of maps.
That would be a different question then - but one that has been asked before.
@Maralc What do you mean be "re-pointing"? You don't have access to that information from the outside?!

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.