If I have a Map
like this:
HashMap<Integer, ComparableObject> map;
and I want to obtain a collection of values sorted using natural ordering, which method is fastest?
(A)
Create an instance of a sortable collection like ArrayList
, add the values, then sort it:
List<ComparableObject> sortedCollection = new ArrayList<ComparableObject>(map.values());
Collections.sort(sortedCollection);
(B)
Create an instance of an ordered collection like TreeSet
, then add the values:
Set<ComparableObject> sortedCollection = new TreeSet<ComparableObject>(map.values());
Note that the resulting collection is never modified, so the sorting only needs to take place once.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…