Removing via an iterator

Removing via an Iterator is the oldest approach available in Java. Mainly, an Iterator allows us to iterate (or traverse) a collection and remove certain elements. The oldest approach also has some drawbacks. First of all, depending on the collection type, removing via an Iterator is prone to ConcurrentModificationException if multiple threads modify the collection. Moreover, removal does not behave the same for all collections (for example, removing from a LinkedList is faster than removing from an ArrayList because the former simply moves the pointer to the next element while the latter needs to shift elements). Nevertheless, the solution is available in the bundled code.

If all you need is the size of Iterable, then consider one of the following approaches:

// for any Iterable
StreamSupport.stream(iterable.spliterator(), false).count();

// for collections
((Collection<?>) iterable).size()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.134.17