Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Iterator for List?

Tags:

Is there an efficient way to iterate through objects in the list in reverse order in dart? I could use indices, but will that cause a performance hit (i.e. if List<E> is built internally using linked list)?

Context: I'm drawing objects from back to front, but need to process them from front to back

Ali

like image 438
Ali Akbar Avatar asked Nov 16 '12 12:11

Ali Akbar


People also ask

How do you reverse a list iterate?

We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.

How do you iterate through a list backwards in C++?

C++ Iterators Reverse Iterators A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.

Which collection allows reverse iterators?

2. Using Apache Common Collections. Apache Common provides ReverseListIterator that we can use to iterate list in reverse order. The first call to next() will return the last element from the list, the next call to next() will return the previous element, and so on.


2 Answers

You can now reverse the iteration of a list in Dart. Use the reversed getter on List.

var fruits = ['apples', 'oranges', 'pears']; Iterable inReverse = fruits.reversed; var fruitsInReverse = inReverse.toList(); print(fruitsInReverse); // [pears, oranges, apples] 

You could shorten this to:

var fruits = ['apples', 'oranges', 'pears']; print(fruits.reversed.toList()); 

See the API docs.

like image 129
Seth Ladd Avatar answered Oct 21 '22 23:10

Seth Ladd


Until the issue #2804 has been fixed, you have to iterate list in reverse order using indices. For your performance concern, it should be good because Lasse R.H. Nielsen once said :

Lists in Dart are intended for random access

like image 40
Alexandre Ardhuin Avatar answered Oct 22 '22 00:10

Alexandre Ardhuin