All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ca.gc.aafc.dina.service.CollectionBackedReadOnlyDinaService Maven / Gradle / Ivy

There is a newer version: 0.132
Show newest version
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