Monday, August 26, 2019

How do you sort the keys in HashMap?

Problem statement:
Write the java code to sort the keys in HashMap.

  1. import java.util.HashMap;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "zz");
  9. m.put("key39", "cc");
  10. m.put("key27", "bb");
  11. Set<String> s = m.keySet();
  12. s = new TreeSet<String>(s);
  13. System.out.println(s);
  14. }
  15. }
Output:
[key12, key27, key39, key45]

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...