Search code examples
javadequesortedset

How to transfer data from a Deque to a SortedSet in Java


I get a Deque<Element> deque and I want to transfer all the elements to the other structure: SortedSet<Element> sortedSet.

And the sequence of elements in sortedSet is just as same as the sequences in which the elements are popped from deque.

For example: if all the elements are popped from deque in a sequence: E01, E02, ..., E10. The sequence of elements stored in sortedSet are also E01, E02, ..., E10.

I don't know how to override the comparator to let the elements store in such a sequence.

Do you know how to do that?


Solution

  • Jane, I wrote a simple code:

    public static void main(String[] args) {
            SortedSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>() {
                @Override
                public int compare(Integer i1, Integer i2) {
                    return 1;
                }
            });
            Deque<Integer> deq = new LinkedList<Integer>();
            deq.add(5);
            deq.add(1);
            deq.add(3);
            set.addAll(deq);
            System.out.println(deq); // 5,1,3
        }
    

    The comparator should always return 1 this way the order stays the same, if this was your question. Warning: this solution violates the Comparable and Set contract. Use it with caution.