A good Sorted List for Java

后端 未结 10 1689
离开以前
离开以前 2020-11-30 02:29

I\'m looking for a good sorted list for java. Googling around give me some hints about using TreeSet/TreeMap. But these components is lack of one thing: random access to an

相关标签:
10条回答
  • 2020-11-30 02:45

    What about using a HashMap? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.

    edit

    A quick search has found LinkedHashMap, which maintains insertion order of your keys. It's not an exact solution, but it's pretty close.

    0 讨论(0)
  • 2020-11-30 02:50

    SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/

    0 讨论(0)
  • 2020-11-30 02:54

    Depending on how you're using the list, it may be worth it to use a TreeSet and then use the toArray() method at the end. I had a case where I needed a sorted list, and I found that the TreeSet + toArray() was much faster than adding to an array and merge sorting at the end.

    0 讨论(0)
  • 2020-11-30 02:55

    This is the SortedList implementation I am using. Maybe this helps with your problem:

    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.LinkedList;
    /**
     * This class is a List implementation which sorts the elements using the
     * comparator specified when constructing a new instance.
     * 
     * @param <T>
     */
    public class SortedList<T> extends ArrayList<T> {
        /**
         * Needed for serialization.
         */
        private static final long serialVersionUID = 1L;
        /**
         * Comparator used to sort the list.
         */
        private Comparator<? super T> comparator = null;
        /**
         * Construct a new instance with the list elements sorted in their
         * {@link java.lang.Comparable} natural ordering.
         */
        public SortedList() {
        }
        /**
         * Construct a new instance using the given comparator.
         * 
         * @param comparator
         */
        public SortedList(Comparator<? super T> comparator) {
            this.comparator = comparator;
        }
        /**
         * Construct a new instance containing the elements of the specified
         * collection with the list elements sorted in their
         * {@link java.lang.Comparable} natural ordering.
         * 
         * @param collection
         */
        public SortedList(Collection<? extends T> collection) {
            addAll(collection);
        }
        /**
         * Construct a new instance containing the elements of the specified
         * collection with the list elements sorted using the given comparator.
         * 
         * @param collection
         * @param comparator
         */
        public SortedList(Collection<? extends T> collection, Comparator<? super T> comparator) {
            this(comparator);
            addAll(collection);
        }
        /**
         * Add a new entry to the list. The insertion point is calculated using the
         * comparator.
         * 
         * @param paramT
         * @return <code>true</code> if this collection changed as a result of the call.
         */
        @Override
        public boolean add(T paramT) {
            int initialSize = this.size();
            // Retrieves the position of an existing, equal element or the 
            // insertion position for new elements (negative).
            int insertionPoint = Collections.binarySearch(this, paramT, comparator);
            super.add((insertionPoint > -1) ? insertionPoint : (-insertionPoint) - 1, paramT);
            return (this.size() != initialSize);
        }
        /**
         * Adds all elements in the specified collection to the list. Each element
         * will be inserted at the correct position to keep the list sorted.
         * 
         * @param paramCollection
         * @return <code>true</code> if this collection changed as a result of the call.
         */
        @Override
        public boolean addAll(Collection<? extends T> paramCollection) {
            boolean result = false;
            if (paramCollection.size() > 4) {
                result = super.addAll(paramCollection);
                Collections.sort(this, comparator);
            }
            else {
                for (T paramT:paramCollection) {
                    result |= add(paramT);
                }
            }
            return result;
        }
        /**
         * Check, if this list contains the given Element. This is faster than the
         * {@link #contains(Object)} method, since it is based on binary search.
         * 
         * @param paramT
         * @return <code>true</code>, if the element is contained in this list;
         * <code>false</code>, otherwise.
         */
        public boolean containsElement(T paramT) {
            return (Collections.binarySearch(this, paramT, comparator) > -1);
        }
        /**
         * @return The comparator used for sorting this list.
         */
        public Comparator<? super T> getComparator() {
            return comparator;
        }
        /**
         * Assign a new comparator and sort the list using this new comparator.
         * 
         * @param comparator
         */
        public void setComparator(Comparator<? super T> comparator) {
            this.comparator = comparator;
            Collections.sort(this, comparator);
        }
    }
    

    This solution is very flexible and uses existing Java functions:

    • Completely based on generics
    • Uses java.util.Collections for finding and inserting list elements
    • Option to use a custom Comparator for list sorting

    Some notes:

    • This sorted list is not synchronized since it inherits from java.util.ArrayList. Use Collections.synchronizedList if you need this (refer to the Java documentation for java.util.ArrayList for details).
    • The initial solution was based on java.util.LinkedList. For better performance, specifically for finding the insertion point (Logan's comment) and quicker get operations (https://dzone.com/articles/arraylist-vs-linkedlist-vs), this has been changed to java.util.ArrayList.
    0 讨论(0)
  • 2020-11-30 02:55

    GlazedLists has a very, very good sorted list implementation

    0 讨论(0)
  • 2020-11-30 02:59

    It seems that you want a list structure with very fast removal and random access by index (not by key) times. An ArrayList gives you the latter and a HashMap or TreeMap give you the former.

    There is one structure in Apache Commons Collections that may be what you are looking for, the TreeList. The JavaDoc specifies that it is optimized for quick insertion and removal at any index in the list. If you also need generics though, this will not help you.

    0 讨论(0)
提交回复
热议问题