Monday, August 26, 2019

How do you sort the values in HashMap?

Problem statement:
Write the java code to sort the values in HashMap.
  1. import java.util.Collection;
  2. import java.util.HashMap;
  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. Collection<String> c = m.values();
  12. c = new TreeSet<String>(c);
  13. System.out.println(c);
  14. }
  15. }
Output:
[aa, bb, cc, zz]

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...