There is usually a better way to do this rather than using iterator.remove (). for example, in your case, the loop is the same as
if(list.size()> 5) list.remove(5);
If you need to use iterator.remove (), you can still use a for loop.
for(Iterator iterator = list.iterator(); iterator.hasNext();) { final Object o = iterator.next(); if (++count == 5) iterator.remove(); o.toString(); }
source share