From 7dd157b9d50bdf48ac8ec3e8b61d880c48846183 Mon Sep 17 00:00:00 2001 From: schrom01 Date: Thu, 20 Oct 2022 21:26:30 +0200 Subject: [PATCH] implemented Methods to sort and filter PlantList --- .../plantList/PlantListModel.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java diff --git a/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java b/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java new file mode 100644 index 0000000..0327e59 --- /dev/null +++ b/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java @@ -0,0 +1,45 @@ +package ch.zhaw.gartenverwaltung.plantList; + +import ch.zhaw.gartenverwaltung.types.Plant; + +import java.util.Comparator; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +public class PlantListModel { + private List plantList; + + /** + * Comparators to create sorted Plant List + */ + public final Comparator sortByName = (Plant o1, Plant o2) -> o1.name().compareTo(o2.name()); + public final Comparator getSortById = (Plant o1, Plant o2) -> Long.compare(o1.id(), o2.id()); + public final Comparator sortBySpacing = (Plant o1, Plant o2) -> o1.spacing() - o2.spacing(); + + /** + * Functions to get Plant Attribute as String + */ + public final Function filterByName = Plant::name; + public final Function filterById = plant -> Long.toString(plant.id()); + + public PlantListModel(List plantList) { + setPlantList(plantList); + } + + public void setPlantList(List plantList) { + this.plantList = plantList; + } + + public List getPlantList() { + return getSortedPlantList(sortByName); + } + + public List getSortedPlantList(Comparator comparator) { + return plantList.stream().sorted(comparator).toList(); + } + + public List getFilteredList(String filterString, Function filterFunction) { + return plantList.stream().filter(plant -> filterFunction.apply(plant).contains(filterString)).toList(); + } +}