简体   繁体   中英

How to reverse the order of SortedSet

I want to print an ordered list in Map using the following:

Map<Float, String> mylist = new HashMap<>();

mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);

SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet());

for (Float i : orderlist) {
    System.out.println(i+" "+mylist.get(i));
}

The above code prints:

5.1 c
10.5 a
12.3 b    

But how do I the print the orderlist in reverse order like below:

12.3 b
10.5 a
5.1 c

If you're willing to store the elements in the SortedSet in reverse order, the only change you need to make is to construct the TreeSet with an appropriate constructor which takes a custom Comparator :

Map<Float, String> mylist = new HashMap<>();

mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);

SortedSet<Float> orderlist = new TreeSet<Float>(Collections.reverseOrder());
orderList.addAll(mylist.keySet());

for (Float i : orderlist) {
    System.out.println(i+" "+mylist.get(i));
}

Note the neat method here is Collections.reverseOrder() which returns a Comparator which compares in the opposite of the natural ordering of elements.

You can also try this :

    Map<Float, String> mylist = new HashMap<Float, String>();
    mylist.put(10.5, a);
    mylist.put(12.3, b);
    mylist.put(5.1, c);

    SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet()).descendingSet();

    for (Float i : orderlist) {
        System.out.println(i+" "+mylist.get(i));
    }

Try to use NavigableSet :

 public NavigableSet<E> descendingSet()

Like this:

  SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet());
  SortedSet<Float> treereverse = new TreeSet<Float>();
  // creating reverse set
  treereverse=(TreeSet)orderlist.descendingSet();

Finally you have treereverse with the reverse order.

You can try this implementation ( source ):

public sealed class OrderedSet<T> : ICollection<T>
{
    private readonly IDictionary<T, LinkedListNode<T>> _dictionary;
    private readonly LinkedList<T> _linkedList;

    public OrderedSet()
        : this(EqualityComparer<T>.Default)
    {
    }

    private OrderedSet(IEqualityComparer<T> comparer)
    {
        _dictionary = new Dictionary<T, LinkedListNode<T>>(comparer);
        _linkedList = new LinkedList<T>();
    }

    public int Count => _dictionary.Count;

    public bool IsReadOnly => _dictionary.IsReadOnly;

    void ICollection<T>.Add(T item)
    {
        Add(item);
    }

    public void Clear()
    {
        _linkedList.Clear();
        _dictionary.Clear();
    }

    public bool Remove(T item)
    {
        var found = _dictionary.TryGetValue(item, out var node);
        if (!found)
        {
            return false;
        }

        _dictionary.Remove(item);
        _linkedList.Remove(node);
        return true;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _linkedList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public bool Contains(T item)
    {
        return _dictionary.ContainsKey(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _linkedList.CopyTo(array, arrayIndex);
    }

    public void Add(T item)
    {
        if (_dictionary.ContainsKey(item))
        {
            return;
        }

        var node = _linkedList.AddLast(item);
        _dictionary.Add(item, node);
    }

    public void Reverse()
    {
        var head = _linkedList.First;
        while (head.Next != null)
        {
            var next = head.Next;
            _linkedList.Remove(next);
            _linkedList.AddFirst(next.Value);
        }
    }
}

Please note that this is an OrderSet which preserves the insertion order unlike SortedSet which keeps the set sorted according to some comparator (eg alphabetically).

I added the Reverse() method from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM