Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to iterate on a LinkedList in a sorted way?

Is possibe to retrive the objects of a LinkedList without sorting it?

class MyClass<T> implements Iterable<T> {

    private LinkedList<T> myList = new LinkedList<>();

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            @Override
            public boolean hasNext() {
                return false;
            }

            @Override
            public T next() {
                // SHOULD RETURN THE ELEMENTS OF MYLIST IN A SORTED WAY
                return null;
            }

        };
    }
}

In this case we can assume that objects of type T have an Integer field for sorting

like image 527
user13121591 Avatar asked Oct 24 '25 00:10

user13121591


1 Answers

It's not possible, unless you create extra methods to sort 'on-the-fly' or store a pre-ordered list in another object (I'm assuming you dont want to change the original list order).

Both methods have costs:

  • You can keep an index of the 'current' index and find the next index looking throu the whole list, but this costs CPU
  • You can create a private copy of the list and sort it, and return this new list, but it costs more memory, and you have to keep the new list updated in case the original list have values changed.
like image 64
Wolfgang Amadeus Avatar answered Oct 26 '25 19:10

Wolfgang Amadeus