How can I sort the keys of a Map in Java?












50















This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.










share|improve this question



























    50















    This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.










    share|improve this question

























      50












      50








      50


      8






      This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.










      share|improve this question














      This is a very basic question, I'm just not that good with Java. I have a Map and I want to get a list or something of the keys in sorted order so I can iterate over them.







      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Feb 20 '09 at 21:57









      BialeckiBialecki

      11.6k287597




      11.6k287597
























          4 Answers
          4






          active

          oldest

          votes


















          73














          Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.



          Map<String, Object> map = new TreeMap<String, Object>();
          /* Add entries to the map in any order. */
          ...
          /* Now, iterate over the map's contents, sorted by key. */
          for (Map.Entry<String, ?> entry : map.entrySet()) {
          System.out.println(entry.getKey() + ": " + entry.getValue());
          }


          If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.



          void process(Map<String, Object> original) {
          Map<String, Object> copy = new TreeMap<String, Object>(original);
          /* Now use "copy", which will have keys in sorted order. */
          ...
          }


          A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.






          share|improve this answer


























          • The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

            – Bialecki
            Feb 20 '09 at 22:03











          • You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

            – Daniel Lew
            Feb 20 '09 at 22:05











          • Ding! erickson levels up.

            – Paul Tomblin
            Feb 20 '09 at 22:08






          • 1





            You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

            – Steve Kuo
            Feb 21 '09 at 1:03






          • 1





            Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

            – erickson
            Feb 22 '09 at 4:06



















          33














          You have several options. Listed in order of preference:




          1. Use a SortedMap:
            SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);

            This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.

          2. There is no #2.

          3. There is no #3, either.

          4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());


          5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet());
            Collections.sort(keys);


          The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.






          share|improve this answer


























          • In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

            – David Z
            Feb 20 '09 at 22:08











          • @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

            – Michael Myers
            Feb 20 '09 at 22:10













          • hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

            – Johannes Schaub - litb
            Feb 20 '09 at 22:14











          • @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

            – Michael Myers
            Feb 20 '09 at 22:17











          • #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

            – erickson
            Feb 20 '09 at 22:28



















          8














          You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)



          All the same, here is how you do it.



          Map<String, Object> map;
          for(String key: new TreeSet<String>(map.keySet()) {
          // accessed in sorted order.
          }





          share|improve this answer































            0














            Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -



            List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());


            One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.






            share|improve this answer


























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f571388%2fhow-can-i-sort-the-keys-of-a-map-in-java%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              73














              Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.



              Map<String, Object> map = new TreeMap<String, Object>();
              /* Add entries to the map in any order. */
              ...
              /* Now, iterate over the map's contents, sorted by key. */
              for (Map.Entry<String, ?> entry : map.entrySet()) {
              System.out.println(entry.getKey() + ": " + entry.getValue());
              }


              If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.



              void process(Map<String, Object> original) {
              Map<String, Object> copy = new TreeMap<String, Object>(original);
              /* Now use "copy", which will have keys in sorted order. */
              ...
              }


              A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.






              share|improve this answer


























              • The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

                – Bialecki
                Feb 20 '09 at 22:03











              • You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

                – Daniel Lew
                Feb 20 '09 at 22:05











              • Ding! erickson levels up.

                – Paul Tomblin
                Feb 20 '09 at 22:08






              • 1





                You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

                – Steve Kuo
                Feb 21 '09 at 1:03






              • 1





                Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

                – erickson
                Feb 22 '09 at 4:06
















              73














              Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.



              Map<String, Object> map = new TreeMap<String, Object>();
              /* Add entries to the map in any order. */
              ...
              /* Now, iterate over the map's contents, sorted by key. */
              for (Map.Entry<String, ?> entry : map.entrySet()) {
              System.out.println(entry.getKey() + ": " + entry.getValue());
              }


              If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.



              void process(Map<String, Object> original) {
              Map<String, Object> copy = new TreeMap<String, Object>(original);
              /* Now use "copy", which will have keys in sorted order. */
              ...
              }


              A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.






              share|improve this answer


























              • The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

                – Bialecki
                Feb 20 '09 at 22:03











              • You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

                – Daniel Lew
                Feb 20 '09 at 22:05











              • Ding! erickson levels up.

                – Paul Tomblin
                Feb 20 '09 at 22:08






              • 1





                You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

                – Steve Kuo
                Feb 21 '09 at 1:03






              • 1





                Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

                – erickson
                Feb 22 '09 at 4:06














              73












              73








              73







              Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.



              Map<String, Object> map = new TreeMap<String, Object>();
              /* Add entries to the map in any order. */
              ...
              /* Now, iterate over the map's contents, sorted by key. */
              for (Map.Entry<String, ?> entry : map.entrySet()) {
              System.out.println(entry.getKey() + ": " + entry.getValue());
              }


              If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.



              void process(Map<String, Object> original) {
              Map<String, Object> copy = new TreeMap<String, Object>(original);
              /* Now use "copy", which will have keys in sorted order. */
              ...
              }


              A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.






              share|improve this answer















              Use a TreeMap, which is an implementation of the SortedMap interface. It presents its keys in sorted order.



              Map<String, Object> map = new TreeMap<String, Object>();
              /* Add entries to the map in any order. */
              ...
              /* Now, iterate over the map's contents, sorted by key. */
              for (Map.Entry<String, ?> entry : map.entrySet()) {
              System.out.println(entry.getKey() + ": " + entry.getValue());
              }


              If you are working with another Map implementation that isn't sorted as you like, you can pass it to the constructor of TreeMap to create a new map with sorted keys.



              void process(Map<String, Object> original) {
              Map<String, Object> copy = new TreeMap<String, Object>(original);
              /* Now use "copy", which will have keys in sorted order. */
              ...
              }


              A TreeMap works with any type of key that implements the Comparable interface, putting them in their "natural" order. For keys that aren't Comparable, or whose natural ordering isn't what you need, you can implement your own Comparator and specify that in the constructor.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 20 '09 at 22:09

























              answered Feb 20 '09 at 21:59









              ericksonerickson

              224k42334431




              224k42334431













              • The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

                – Bialecki
                Feb 20 '09 at 22:03











              • You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

                – Daniel Lew
                Feb 20 '09 at 22:05











              • Ding! erickson levels up.

                – Paul Tomblin
                Feb 20 '09 at 22:08






              • 1





                You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

                – Steve Kuo
                Feb 21 '09 at 1:03






              • 1





                Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

                – erickson
                Feb 22 '09 at 4:06



















              • The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

                – Bialecki
                Feb 20 '09 at 22:03











              • You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

                – Daniel Lew
                Feb 20 '09 at 22:05











              • Ding! erickson levels up.

                – Paul Tomblin
                Feb 20 '09 at 22:08






              • 1





                You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

                – Steve Kuo
                Feb 21 '09 at 1:03






              • 1





                Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

                – erickson
                Feb 22 '09 at 4:06

















              The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

              – Bialecki
              Feb 20 '09 at 22:03





              The code I'm consuming gives me a Map object, so how do I then convert it into a TreeMap or use a TreeMap to do the sorting?

              – Bialecki
              Feb 20 '09 at 22:03













              You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

              – Daniel Lew
              Feb 20 '09 at 22:05





              You can create the TreeMap using a constructor whose parameter is any Map. Also, congratulations erickson (I assume, since you're only 5 rep away from 10k).

              – Daniel Lew
              Feb 20 '09 at 22:05













              Ding! erickson levels up.

              – Paul Tomblin
              Feb 20 '09 at 22:08





              Ding! erickson levels up.

              – Paul Tomblin
              Feb 20 '09 at 22:08




              1




              1





              You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

              – Steve Kuo
              Feb 21 '09 at 1:03





              You would better off sorting keys (place in a TreeSet) then calling get on the original Map. Creating a new TreeMap results in everything getting rehashed.

              – Steve Kuo
              Feb 21 '09 at 1:03




              1




              1





              Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

              – erickson
              Feb 22 '09 at 4:06





              Steve, that's incorrect. No hashing occurs with a TreeMap; it's a red-black tree. Anyway, a TreeSet delegates to an internal TreeMap, so creating a TreeSet, iterating over its keys, and using them to perform an O(log(n)) lookup in another tree would be confusing and inefficient.

              – erickson
              Feb 22 '09 at 4:06













              33














              You have several options. Listed in order of preference:




              1. Use a SortedMap:
                SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);

                This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.

              2. There is no #2.

              3. There is no #3, either.

              4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());


              5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet());
                Collections.sort(keys);


              The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.






              share|improve this answer


























              • In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

                – David Z
                Feb 20 '09 at 22:08











              • @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

                – Michael Myers
                Feb 20 '09 at 22:10













              • hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

                – Johannes Schaub - litb
                Feb 20 '09 at 22:14











              • @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

                – Michael Myers
                Feb 20 '09 at 22:17











              • #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

                – erickson
                Feb 20 '09 at 22:28
















              33














              You have several options. Listed in order of preference:




              1. Use a SortedMap:
                SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);

                This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.

              2. There is no #2.

              3. There is no #3, either.

              4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());


              5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet());
                Collections.sort(keys);


              The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.






              share|improve this answer


























              • In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

                – David Z
                Feb 20 '09 at 22:08











              • @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

                – Michael Myers
                Feb 20 '09 at 22:10













              • hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

                – Johannes Schaub - litb
                Feb 20 '09 at 22:14











              • @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

                – Michael Myers
                Feb 20 '09 at 22:17











              • #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

                – erickson
                Feb 20 '09 at 22:28














              33












              33








              33







              You have several options. Listed in order of preference:




              1. Use a SortedMap:
                SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);

                This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.

              2. There is no #2.

              3. There is no #3, either.

              4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());


              5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet());
                Collections.sort(keys);


              The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.






              share|improve this answer















              You have several options. Listed in order of preference:




              1. Use a SortedMap:
                SortedMap<whatever> myNewMap = new TreeMap<whatever>(myOldMap);

                This is vastly preferable if you want to iterate more than once. It keeps the keys sorted so you don't have to sort them before iterating.

              2. There is no #2.

              3. There is no #3, either.

              4. SortedSet<whatever> keys = new TreeSet<whatever>(myMap.keySet());


              5. List<whatever> keys = new ArrayList<whatever>(myMap.keySet());
                Collections.sort(keys);


              The last two will get you what you want, but should only be used if you only want to iterate once and then forget the whole thing.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 20 '09 at 22:12

























              answered Feb 20 '09 at 22:04









              Michael MyersMichael Myers

              158k38261282




              158k38261282













              • In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

                – David Z
                Feb 20 '09 at 22:08











              • @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

                – Michael Myers
                Feb 20 '09 at 22:10













              • hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

                – Johannes Schaub - litb
                Feb 20 '09 at 22:14











              • @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

                – Michael Myers
                Feb 20 '09 at 22:17











              • #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

                – erickson
                Feb 20 '09 at 22:28



















              • In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

                – David Z
                Feb 20 '09 at 22:08











              • @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

                – Michael Myers
                Feb 20 '09 at 22:10













              • hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

                – Johannes Schaub - litb
                Feb 20 '09 at 22:14











              • @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

                – Michael Myers
                Feb 20 '09 at 22:17











              • #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

                – erickson
                Feb 20 '09 at 22:28

















              In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

              – David Z
              Feb 20 '09 at 22:08





              In step #4, you could also create a TreeSet (a sorted set) instead of a list, which saves you from making an explicit call to sort().

              – David Z
              Feb 20 '09 at 22:08













              @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

              – Michael Myers
              Feb 20 '09 at 22:10







              @David: I did think of that, but for some reason I forgot that it was possible to iterate over a Set. It does require sorting every time, though.

              – Michael Myers
              Feb 20 '09 at 22:10















              hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

              – Johannes Schaub - litb
              Feb 20 '09 at 22:14





              hmm i like the #4 . why does it require more sorting than #1 ? i would have thought it was equally good

              – Johannes Schaub - litb
              Feb 20 '09 at 22:14













              @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

              – Michael Myers
              Feb 20 '09 at 22:17





              @litb: If you're dumping the map into a TreeMap every time you want to iterate over it, then you're right, they are the same.

              – Michael Myers
              Feb 20 '09 at 22:17













              #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

              – erickson
              Feb 20 '09 at 22:28





              #4 isn't as good as #1 if you need the values from the map too. Iterating over entries saves the extra lookup for the value.

              – erickson
              Feb 20 '09 at 22:28











              8














              You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)



              All the same, here is how you do it.



              Map<String, Object> map;
              for(String key: new TreeSet<String>(map.keySet()) {
              // accessed in sorted order.
              }





              share|improve this answer




























                8














                You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)



                All the same, here is how you do it.



                Map<String, Object> map;
                for(String key: new TreeSet<String>(map.keySet()) {
                // accessed in sorted order.
                }





                share|improve this answer


























                  8












                  8








                  8







                  You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)



                  All the same, here is how you do it.



                  Map<String, Object> map;
                  for(String key: new TreeSet<String>(map.keySet()) {
                  // accessed in sorted order.
                  }





                  share|improve this answer













                  You can create a sorted collection when iterating but it make more sense to have a sorted map in the first place. (As has already been suggested)



                  All the same, here is how you do it.



                  Map<String, Object> map;
                  for(String key: new TreeSet<String>(map.keySet()) {
                  // accessed in sorted order.
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 20 '09 at 22:07









                  Peter LawreyPeter Lawrey

                  448k56575979




                  448k56575979























                      0














                      Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -



                      List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());


                      One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.






                      share|improve this answer






























                        0














                        Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -



                        List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());


                        One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.






                        share|improve this answer




























                          0












                          0








                          0







                          Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -



                          List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());


                          One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.






                          share|improve this answer















                          Apart from the methods mentioned in other answers, with Java 8 streams, another shorthand to get a sorted key list from a map would be -



                          List<T> sortedKeys = myMap.keySet().stream().sorted().collect(Collectors.toList());


                          One could actually get stuff done after .sorted() as well (like using a .map(...) or a .forEach(...)), instead of collecting it in the list and then iterating over the list.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 16 '18 at 10:17









                          ayaio

                          58.7k20134189




                          58.7k20134189










                          answered Nov 16 '18 at 10:15









                          ShreyasShreyas

                          36836




                          36836






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f571388%2fhow-can-i-sort-the-keys-of-a-map-in-java%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              List item for chat from Array inside array React Native

                              Thiostrepton

                              Caerphilly