Sort or sort the collection

Suppose an application creates several data structures HashMap<String, MyClass>, each of which contains from tens to hundreds of Comparabletype objects MyClassthat must end with one and sorted Collection.

Two possible implementations of this function return a SortedSet or sorted list, as shown below:

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

Was there any clear performance advantage for any of the above methods?

Is there a faster way to implement the same functionality?

+3
source share
3 answers

Some problems with your sorted list method:

ArrayLists . , , . , ArrayList .

. ? ( , ) Java

, , TreeSet . , , Set.toArray(), .

+4

, ?

, .

, , , JDK, JIT- ..

- .

+2

Sets and lists differ in nature in the sense that sets do not preserve duplicates. You can have only one instance of an object. Lists allow you to save duplicates.

Thus, sets do more work, therefore, they are slower.

+1
source

All Articles