Collection<Deployment> () { //assumed myLock Map<Deployment, DeploymentImpl<?>> orderedDeployments = new TreeMap<>(myDeploymentComparator); List<LocalDeploymentImpl<?>> matchedLocalsBefore = new ArrayList<>(); for (LocalDeploymentImpl<?> localDeployment : myLocalDeployments.values()) { if (localDeployment.hasRemoteDeloyment()) { matchedLocalsBefore.add(localDeployment); } localDeployment.setRemoteDeployment(null); orderedDeployments.put(localDeployment, localDeployment); } Set<Deployment> result = new LinkedHashSet<>(orderedDeployments.keySet()); for (DeploymentImpl<?> remoteDeployment : myRemoteDeployments.values()) { DeploymentImpl<?> deployment = orderedDeployments.get(remoteDeployment); if (deployment != null) { if (deployment instanceof LocalDeploymentImpl) { ((LocalDeploymentImpl<?>)deployment).setRemoteDeployment(remoteDeployment); } } else { orderedDeployments.put(remoteDeployment, remoteDeployment); } } final DeploymentStatus finishedExternally = DeploymentStatus.NOT_DEPLOYED; for (LocalDeploymentImpl<?> nextLocal : matchedLocalsBefore) { if (!nextLocal.hasRemoteDeloyment()) { nextLocal.changeState(nextLocal.getStatus(), finishedExternally, null, null); } } result.addAll(orderedDeployments.keySet()); return result; }