entaxy-public/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/DependencySorter.java

55 lines
1.7 KiB
Java

/*-
* ~~~~~~licensing~~~~~~
* test-producers
* ==========
* Copyright (C) 2020 - 2022 EmDev LLC
* ==========
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ~~~~~~/licensing~~~~~~
*/
package ru.entaxy.platform.base.support;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class DependencySorter {
public static interface DependencyProvider<T> {
List<T> getDependencies(T inspectedObject);
}
public static <T> List<T> getSortedList(List<T> origin, DependencyProvider<T> provider) throws Exception {
List<T> result = new LinkedList<>();
// add independent objects
result.addAll(
origin.stream().filter(obj -> provider.getDependencies(obj).isEmpty())
.collect(Collectors.toList())
);
while (result.size() < origin.size()) {
List<T> nextObjects = origin.stream().filter(obj->!result.contains(obj))
.filter(obj->result.containsAll(provider.getDependencies(obj)))
.collect(Collectors.toList());
if (nextObjects.isEmpty())
// TODO create more informative exception
throw new Exception("Contains unsatisfied dependencies");
result.addAll(nextObjects);
}
return result;
}
}