Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.BiPredicate; public class Main { public static <E> void updateList(List<E> origList, Collection<? extends E> updateList) { updateList(origList, updateList, true, true, true, Objects::equals); } public static <E> void updateList(List<E> origList, Collection<? extends E> updateList, boolean add, boolean replace, boolean remove) { updateList(origList, updateList, add, replace, remove, Objects::equals); } public static <E> void updateList(List<E> origList, Collection<? extends E> updateList, boolean add, boolean replace, boolean remove, BiPredicate<? super E, ? super E> comparer) { updateList(origList, updateList, add, replace, remove, comparer, (List<E> list, Collection<? extends E> itemsToAdd) -> origList.addAll(itemsToAdd)); } private static <E> void updateList(List<E> origList, Collection<? extends E> updateList, boolean add, boolean replace, boolean remove, BiPredicate<? super E, ? super E> equalTester, BiConsumer<List<E>, Collection<? extends E>> adder) { List<E> itemsToRemove = null; List<E> itemsToAdd = null; for (E update : updateList) { boolean origListContainsUpdate = false; ListIterator<E> origIter = origList.listIterator(); while (origIter.hasNext()) { E orig = origIter.next(); if (equalTester.test(orig, update)) { origListContainsUpdate = true; if (remove) { if (itemsToRemove == null) { itemsToRemove = new ArrayList<>(origList); } itemsToRemove.remove(orig); } if (replace) { origIter.set(update); } break; } } if (!origListContainsUpdate && add) { if (itemsToAdd == null) { itemsToAdd = new ArrayList<>(); } itemsToAdd.add(update); } } if (remove) { if (itemsToRemove != null) { origList.removeAll(itemsToRemove); } else { origList.clear(); } } if (itemsToAdd != null) { adder.accept(origList, itemsToAdd); } } }