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);