From 301c7bf7850cef454d208170e9813b910515a63f Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 5 Dec 2018 15:48:21 +0100 Subject: [PATCH] [New] Added SearchResult.toSingleton() for optional result --- .../java/li/strolch/search/SearchResult.java | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/li.strolch.agent/src/main/java/li/strolch/search/SearchResult.java b/li.strolch.agent/src/main/java/li/strolch/search/SearchResult.java index 47e07cb8b..aa762a1ec 100644 --- a/li.strolch.agent/src/main/java/li/strolch/search/SearchResult.java +++ b/li.strolch.agent/src/main/java/li/strolch/search/SearchResult.java @@ -1,9 +1,8 @@ package li.strolch.search; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import static li.strolch.utils.collections.CollectionsHelper.singletonCollector; + +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -11,7 +10,6 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import li.strolch.utils.collections.CollectionsHelper; import li.strolch.utils.collections.Paging; /** @@ -135,6 +133,19 @@ public class SearchResult { return Paging.asPage(this.stream.collect(Collectors.toList()), offset, limit); } + /** + * Returns the single element in the stream, or throws an {@link IllegalStateException} if the stream does not + * contain 1 and only 1 element + * + * @return the single element in the stream + * + * @throws IllegalStateException + * if not 1 and only 1 element is in the stream + */ + public Optional toSingleton() { + return Optional.of(this.stream.collect(singletonCollector(true))); + } + /** * Returns the single element in the stream, or throws an {@link IllegalStateException} if the stream does not * contain 1 and only 1 element @@ -145,7 +156,7 @@ public class SearchResult { * if not 1 and only 1 element is in the stream */ public T toSingleton(Supplier errorMsgSupplier) throws IllegalStateException { - return this.stream.collect(CollectionsHelper.singletonCollector(errorMsgSupplier)); + return this.stream.collect(singletonCollector(errorMsgSupplier)); } /**