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)
    });
Nan Y
  • 37
  • 1
  • 7
  • 1
    You can get sorted map by `TreeMap sorted = new TreeMap<>(resulting);`. –  Aug 11 '17 at 09:07
  • Have a look into https://stackoverflow.com/a/39533189/7403180 – sForSujit Aug 11 '17 at 09: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? – Nan Y Aug 11 '17 at 09:39
  • I appreciate the quick comeback. Feel free to practice upvoting now that you reached that level ;-) – GhostCat Aug 11 '17 at 18:29

1 Answers1

8

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 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. – Nan Y Aug 11 '17 at 09:40
  • That would be a different question then - but one that has been asked [before](https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java). – GhostCat Aug 11 '17 at 09:45
  • @Maralc What do you mean be "re-pointing"? You don't have access to that information from the outside?! – GhostCat Sep 26 '22 at 06:07