ca.gc.aafc.dina.service.CollectionBackedReadOnlyDinaService Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dina-base-api Show documentation
Show all versions of dina-base-api Show documentation
Base DINA API package for Java built on SpringBoot and Crnk
package ca.gc.aafc.dina.service;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Implementation of {@link PredicateBasedReadOnlyDinaService} that is backed by a Java collection.
*
* @param
* @param
*/
public abstract class CollectionBackedReadOnlyDinaService implements PredicateBasedReadOnlyDinaService {
private final Collection collection;
private final Function getKeyFunction;
public CollectionBackedReadOnlyDinaService(Collection collection,
Function getKeyFunction) {
this.collection = collection;
this.getKeyFunction = getKeyFunction;
}
@Override
public R findOne(K key) {
return collection.stream()
.filter(r -> getKeyFunction.apply(r).equals(key)).findFirst()
.orElse(null);
}
@Override
public List findAll(Predicate predicate, Comparator sortComparator, Integer pageOffset, Integer pageLimit) {
Stream stream = collection.stream();
if (predicate != null) {
stream = stream.filter(predicate);
}
if (sortComparator != null) {
stream = stream.sorted(sortComparator);
}
if (pageOffset != null) {
stream = stream.skip(pageOffset);
}
if (pageLimit != null) {
stream = stream.limit(pageLimit);
}
return stream.collect(Collectors.toList());
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy