Assume an application producing a number of HashMap<String, MyClass> data structures, each containing dozens to hundreds of Comparable objects of type MyClass, which need to end up in a single and sorted Collection.
Two possible implementations of this functionality return a SortedSet or a sorted List, as follows:
public static Set<MyClass> getSortedSet(HashMap<String, MyClass>... allMaps)
{
SortedSet<MyClass> set = new TreeSet<MyClass>();
Collection<MyClass> c;
for (HashMap<String, MyClass> map:allMaps)
{
c = map.values();
set.addAll(c);
}
return set;
}
public static List<MyClass> getSortedList(HashMap<String, MyClass>... allMaps)
{
List<MyClass> list = new ArrayList<MyClass>();
Collection<MyClass> c;
for (HashMap<String, MyClass> map:allMaps)
{
c = map.values();
list.addAll(c);
}
Collections.sort(list);
return list;
}
Would there be any clear performance advantage to any of the above 2 methods?
Is there a faster way of implementing the same functionality?
Some problems with your sorted list method:
ArrayLists are backed by arrays. Whenever you add a new element, it might have to grow the array behind the scenes. If you want to use this approach, you should create the ArrayList of the proper size before hand.
The sorting after you add all elements seems non-optimal. Why not add elements into the list at their correct position? (Use a sorted collection then turn into a list) A good Sorted List for Java
To actually answer you question, I would go with the approach that uses the TreeSet behind the scenes. Because, if the user wants, they can always do Set.toArray() and then have a list.