public void add(final MethodsChain newChain) { if (myResult.isEmpty()) { myResult.add(newChain); return; } boolean doAdd = true; final Stack<Integer> indexesToRemove = new Stack<>(); for (int i = 0; i < myResult.size(); i++) { final MethodsChain chain = myResult.get(i); // final MethodsChain.CompareResult r = MethodsChain.compare(chain, newChain, myContext); switch (r) { case LEFT_CONTAINS_RIGHT: indexesToRemove.add(i); break; case RIGHT_CONTAINS_LEFT: case EQUAL: doAdd = false; break; case NOT_EQUAL: break; } } while (!indexesToRemove.empty()) { myResult.remove((int) indexesToRemove.pop()); } if (doAdd) { myResult.add(newChain); } }