use of javaslang.collection.List in project javaslang by javaslang.
the class Future method find.
/**
* Returns a {@code Future} that eventually succeeds with the first result of the given {@code Future}s which
* matches the given {@code predicate}. If no result matches, the {@code Future} will contain {@link Option.None}.
* <p>
* The returned {@code Future} is backed by the given {@link ExecutorService}.
*
* @param executorService An executor service.
* @param futures An iterable of futures.
* @param predicate A predicate that tests successful future results.
* @param <T> Result type of the futures.
* @return A Future of an {@link Option} of the first result of the given {@code futures} that satisfies the given {@code predicate}.
* @throws NullPointerException if one of the arguments is null
*/
static <T> Future<Option<T>> find(ExecutorService executorService, Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) {
Objects.requireNonNull(executorService, "executorService is null");
Objects.requireNonNull(futures, "futures is null");
Objects.requireNonNull(predicate, "predicate is null");
final Promise<Option<T>> promise = Promise.make(executorService);
final List<Future<? extends T>> list = List.ofAll(futures);
if (list.isEmpty()) {
promise.success(Option.none());
} else {
final AtomicInteger count = new AtomicInteger(list.length());
list.forEach(future -> future.onComplete(result -> {
synchronized (count) {
if (!promise.isCompleted()) {
final boolean wasLast = count.decrementAndGet() == 0;
result.filter(predicate).onSuccess(value -> promise.trySuccess(Option.some(value))).onFailure(ignored -> {
if (wasLast) {
promise.trySuccess(Option.none());
}
});
}
}
}));
}
return promise.future();
}
use of javaslang.collection.List in project javaslang by javaslang.
the class Euler43Test method tenDigitPandigitalsWithProperty.
private static Seq<Long> tenDigitPandigitalsWithProperty() {
final CharSeq ALL_DIGITS = CharSeq.of("0123456789");
final List<Integer> DIVISORS = List.of(2, 3, 5, 7, 11, 13, 17);
return ALL_DIGITS.combinations(2).flatMap(CharSeq::permutations).flatMap(firstTwoDigits -> DIVISORS.foldLeft(List.of(firstTwoDigits), (accumulator, divisor) -> accumulator.flatMap(digitsSoFar -> ALL_DIGITS.removeAll(digitsSoFar).map(nextDigit -> digitsSoFar.append(nextDigit))).filter(digitsToTest -> digitsToTest.takeRight(3).parseInt() % divisor == 0))).map(tailDigitsWithProperty -> tailDigitsWithProperty.prepend(ALL_DIGITS.removeAll(tailDigitsWithProperty).head())).map(CharSeq::parseLong);
}
Aggregations