ListIterator

I'm quite ashamed right now (after like 15+ years using Java pretty extensively), but I just recently figure out that ListIterator exists. Maybe, I knew about it and just forgot? Many times I avoided modifying the list while iterating over it, just because this would result in ConcurrentModificationException, and I had to come up with some tricky ways.

ListIterator allows adding and removing elements in the list while traversing it. It also supports moving backwards, making it a great tool for some algorithm, especially those based on Linked List. And ListIterator works just fine for ArrayLists too. Here is a simple example. Lets write the code that if finds value about 100, removes it with previous and next value, but if finds values below 10, duplicates it.
  List numbers = new LinkedList<>(); // Could be ArrayList as easily
  numbers.add(10);
  numbers.add(20);
  numbers.add(30);
  numbers.add(110);
  numbers.add(45);
  numbers.add(3);
  numbers.add(35);

  ListIterator iterator = numbers.listIterator();
  while (iterator.hasNext()) {
    Integer number = iterator.next();
    if (number > 100) {
        iterator.previous(); // move prior 110
        if (iterator.hasPrevious()) {
            iterator.previous(); // move prior 30
            iterator.remove(); // remove 30
            iterator.next(); // move prior 110
        }
        iterator.remove(); // remove 110
        if (iterator.hasNext()) {
            iterator.next(); // remove prior 45
            iterator.remove(); // remove 45
        }
    } else if (number < 10) {
        iterator.add(number);
    }
  }
  
  System.out.println(numbers);
prints..
  [10, 20, 3, 3, 35]
I love the moments, when I find learn something, especially if it is going to help me do my work better.