2 Given: 34. HashMap props = new HashMap(); 35. props.put("key45", "some value"); 36. props.put("key12", "some other value"); 37. props.put("key39", "yet another value"); 38. Set s = props.keySet(); 39. // insert code here What, inserted at line 39, will sort the keys in the props HashMap?

  1. A. Arrays.sort(s);

  2. B. s = new TreeSet(s);

  3. C. Collections.sort(s);

  4. D. s = new SortedSet(s);


Correct Option: B
Explanation:

To sort the keys in the props HashMap, the user needs to know about the different data structures available in Java that can help to sort a collection of keys. The user also needs to know about the methods provided by the Java Collections framework that can be used to perform sorting on collections.

Option A: Arrays.sort(s); is incorrect. The Arrays.sort() method is used to sort arrays, not sets or maps. It will result in a compilation error.

Option B: s = new TreeSet(s); is correct. A TreeSet is a sorted set that orders its elements based on their natural ordering or based on a comparator provided at the time of creation. By creating a new TreeSet using the Set of keys from the props HashMap, the keys will be automatically sorted.

Option C: Collections.sort(s); is incorrect. The Collections.sort() method is used to sort lists, not sets or maps. It will result in a compilation error.

Option D: s = new SortedSet(s); is incorrect. SortedSet is an interface and cannot be instantiated. Moreover, the Set obtained from the props HashMap is already sorted.

Therefore, the correct answer is:

The Answer is: B. s = new TreeSet(s);

Find more quizzes: