Monday, August 26, 2019

Which of the following option will sort the keys in HashMap ?

Problem statement:
Given java code as follows, can you find out the correct option 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", "bb");
  9. m.put("key39", "cc");
  10. Set<String> s = m.keySet();
  11.   // code goes here
  12. s = new TreeSet(s);
  13.  }
  14. }
  • Arrays.sort(s);
  • s = new TreeSet(s);
  • Collections.sort(s);
  • s = new SortedSet(s);
Correct option: 
s = new TreeSet(s);
Explanation:
Arrays.sort(s) // sorts for static array 
Collection.sort(s) // sort the List type of object not Set type
s =new SortedSet(s); // SortedSet is an interface

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...