From eb158c0648a9ab3d32ef8ba9f7e0dedfa07639ee Mon Sep 17 00:00:00 2001 From: Paul Schaub Date: Thu, 30 Jun 2022 13:16:44 +0200 Subject: [PATCH] Add useful collection/iterator util methods --- .../org/pgpainless/util/CollectionUtils.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/pgpainless-core/src/main/java/org/pgpainless/util/CollectionUtils.java b/pgpainless-core/src/main/java/org/pgpainless/util/CollectionUtils.java index e901eecc..c1ed5a02 100644 --- a/pgpainless-core/src/main/java/org/pgpainless/util/CollectionUtils.java +++ b/pgpainless-core/src/main/java/org/pgpainless/util/CollectionUtils.java @@ -62,6 +62,54 @@ public final class CollectionUtils { return false; } + public static boolean contains(Iterator iterator, T t) { + return hasMatching(iterator, new Filter() { + @Override + public boolean accept(T t0) { + return t.equals(t0); + } + }); + } + + public static boolean hasMatching(Iterator iterator, Filter filter) { + T matchingItem = firstMatching(iterator, filter); + return matchingItem != null; + } + + public static T firstMatching(Iterator iterator, Filter filter) { + while (iterator.hasNext()) { + T item = iterator.next(); + if (filter.accept(item)) { + return item; + } + } + return null; + } + + public static Iterator map(Iterator iterator, Mapper valueMapper) { + return new Iterator() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public N next() { + return valueMapper.mapValue(iterator.next()); + } + }; + } + + @FunctionalInterface + interface Filter { + boolean accept(T t); + } + + @FunctionalInterface + interface Mapper { + N mapValue(T item); + } + /** * Add all items from the iterator to the collection. *