/** * Removes everything in toRemove from the list of lists, elements. Called both by GroupedList and * GroupedListHelper. */ private static <E> List<Object> remove(List<Object> elements, Set<E> toRemove) { int removedCount = 0; // elements.size is an upper bound of the needed size. Since normally removal happens just // before the list is finished and compressed, optimizing this size isn't a concern. List<Object> newElements = new ArrayList<>(elements.size()); for (Object obj : elements) { if (obj instanceof List) { ImmutableList.Builder<E> newGroup = new ImmutableList.Builder<>(); @SuppressWarnings("unchecked") List<E> oldGroup = (List<E>) obj; for (E elt : oldGroup) { if (toRemove.contains(elt)) { removedCount++; } else { newGroup.add(elt); } } ImmutableList<E> group = newGroup.build(); addItem(group, newElements); } else { if (toRemove.contains(obj)) { removedCount++; } else { newElements.add(obj); } } } Preconditions.checkState( removedCount == toRemove.size(), "%s %s %s", elements, toRemove, newElements); return newElements; }