Search code examples
javadata-structurescollectionslinked-list

How to list elements maintaining order and reverse iteration?


What is the best list/set/array in Java that combines the following aspects:

  • maintain order of added elements
  • make if possible to both iterate forwards and backwards
  • of course good performance

I thought about a LinkedList, I then could insert elements by add(0, element) which would simulate a reverse order. Most of the time I will be using backwards iteration, so using this I can just iterate trough. And if not, I can list.listIterator().hasPrevious().

But are there better approaches?


Solution

  • ArrayList is an efficient, commonly used list data structure in Java, and is typically the mutable list type used most frequently in Java programs. Unless you need functionality provided by a more specific list type, or are creating a fixed immutable list (in which case the List.of methods would likely be better), I'd recommend ArrayList.

    As of Java 21, a reversed view of any List can be obtained using that object's reversed method. This can be used to iterate through the list backwards.

    List<String> list = new ArrayList<>(List.of(1, 2, 3));
    
    list.forEach(e -> System.out::println); // Forwards iteration
    list.reversed().forEach(e -> System.out::println); // Backwards iteration