Advertisement
GeneralGDA

Fast array list eraser

May 6th, 2015
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.19 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. /**
  4.  * @author: GeneralGDA
  5.  * @since: 19.02.2009; 21:53:50
  6.  */
  7. public final class ArrayListCleaner
  8. {
  9.     private ArrayListCleaner()
  10.     {
  11.         throw new UnsupportedOperationException();
  12.     }
  13.  
  14.     /**
  15.      * Algorithm: check element. If it expired - move to it's position
  16.      * element from containers' end.
  17.      *
  18.      * @param list list to clear of invalid elements.
  19.      * @param validator invalid object detector.
  20.      * @return true if at least one object was deleted.
  21.      */
  22.     public static <T> boolean removeInvalidObjects(final ArrayList<T> list, final Validator<T> validator)
  23.     {
  24.         if (null == list || list.isEmpty() || null == validator)
  25.         {
  26.             return false;
  27.         }
  28.  
  29.         boolean atLeastOneBadFound = false;
  30.  
  31.         int lastIndex = list.size() - 1;
  32.         for (int i = 0; i < lastIndex; i++)
  33.         {
  34.             final T element = list.get(i);
  35.             if (validator.process(element))
  36.             {
  37.                 atLeastOneBadFound = true;
  38.                 list.set(i, list.get(lastIndex));
  39.                 list.remove(lastIndex);
  40.                 lastIndex--;
  41.                 i--;
  42.             }
  43.         }
  44.  
  45.         final T element = list.get(lastIndex);
  46.         if (validator.process(element))
  47.         {
  48.             atLeastOneBadFound = true;
  49.             list.remove(lastIndex);
  50.         }
  51.  
  52.         return atLeastOneBadFound;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement