You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/07/30 21:34:50 UTC
(groovy) branch master updated: GROOVY-12215: fat-free (functional-interface) twins for mapping/filtering DGM methods
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new ef7780a055 GROOVY-12215: fat-free (functional-interface) twins for mapping/filtering DGM methods
ef7780a055 is described below
commit ef7780a055fd567bb97e19d26118524f02634ef9
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Jul 30 20:24:20 2026 +1000
GROOVY-12215: fat-free (functional-interface) twins for mapping/filtering DGM methods
Add java.util.function twins beside the Closure overloads of collectMany,
collectingMany, countBy, split, groupBy and takeWhile/dropWhile, in both
DefaultGroovyMethods (collection/map receivers) and ArrayGroovyMethods (array
receivers). Map receivers take BiFunction/BiPredicate; other receivers take
Function/Predicate. Follows the conventions established in GROOVY-12054
(PECS wildcards, @since 6.0.0, javadoc examples, plain SAM overloads).
32 new overloads (25 in DGM, 7 in ArrayGroovyMethods). The TakeWhile/DropWhile
iterators now hold a Predicate, with the Closure constructors adapting to it.
Regression tests added to LambdasTest.
---
.../groovy/runtime/ArrayGroovyMethods.java | 143 ++++++
.../groovy/runtime/DefaultGroovyMethods.java | 566 ++++++++++++++++++++-
.../org/apache/groovy/util/LambdasTest.groovy | 58 +++
3 files changed, 759 insertions(+), 8 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/runtime/ArrayGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/ArrayGroovyMethods.java
index 13d42063e7..f7f48f398a 100644
--- a/src/main/java/org/codehaus/groovy/runtime/ArrayGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/ArrayGroovyMethods.java
@@ -1051,6 +1051,25 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return collectMany(self, new ArrayList<>(), projection);
}
+ /**
+ * Projects each item from a source array to a collection and concatenates
+ * (flattens) the resulting collections into a single list. A "fat-free" variant of
+ * {@link #collectMany(Object[], Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = 1..10
+ * def squaresAndCubesOfEvens = nums.collectMany(n -> n % 2 ? [] : [n**2, n**3])
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
+ * </pre>
+ *
+ * @param self an array
+ * @param projection a projecting function returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @since 6.0.0
+ */
+ public static <T, E> List<T> collectMany(E[] self, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
+ }
+
/**
* Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list.
* <pre class="language-groovy groovyTestCase">
@@ -1069,6 +1088,26 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return DefaultGroovyMethods.collectMany(new ArrayIterable<>(self), collector, projection);
}
+ /**
+ * Projects each item from a source array to a result collection and concatenates
+ * (flattens) the resulting collections adding them into the <code>collector</code>.
+ * A "fat-free" variant of {@link #collectMany(Object[], Collection, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 4, 5]
+ * def origPlusIncrements = nums.collectMany([] as Set, n -> [n, n + 1])
+ * assert origPlusIncrements.size() == nums.size() + 1
+ * </pre>
+ *
+ * @param self an array
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting function returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) into it
+ * @since 6.0.0
+ */
+ public static <T, E, C extends Collection<T>> C collectMany(E[] self, C collector, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return DefaultGroovyMethods.collectMany(new ArrayIterable<>(self), collector, projection);
+ }
+
//--------------------------------------------------------------------------
// column
@@ -1559,6 +1598,24 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return DefaultGroovyMethods.countBy(new ArrayIterator<>(self), closure);
}
+ /**
+ * Sorts all array members into groups determined by the supplied mapping function
+ * and counts the group size. A "fat-free" variant of
+ * {@link #countBy(Object[], Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 4, 5]
+ * assert [1: 3, 0: 2] == nums.countBy(n -> n % 2)
+ * </pre>
+ *
+ * @param self an array to group and count
+ * @param function a function mapping items to the frequency keys
+ * @return a new Map grouped by keys with frequency counts
+ * @since 6.0.0
+ */
+ public static <K, E> Map<K, Integer> countBy(E[] self, Function<? super E, ? extends K> function) {
+ return DefaultGroovyMethods.countBy(new ArrayIterator<>(self), function);
+ }
+
/**
* Creates a multiset-like map of the array members.
* <p>
@@ -1680,6 +1737,31 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return drop(self, num);
}
+ /**
+ * Returns a suffix of an array where elements are dropped from the front while the predicate is satisfied.
+ * A "fat-free" variant of {@link #dropWhile(Object[], Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 0, 4]
+ * assert nums.dropWhile(n -> n < 3).toList() == [3, 0, 4]
+ * </pre>
+ *
+ * @param self the original array
+ * @param condition the predicate that must evaluate to true to continue dropping elements
+ * @return the shortest suffix of the given array such that its first element does not pass the given predicate
+ * @since 6.0.0
+ */
+ public static <T> T[] dropWhile(T[] self, Predicate<? super T> condition) {
+ int num = 0;
+ while (num < self.length) {
+ if (condition.test(self[num])) {
+ num += 1;
+ } else {
+ break;
+ }
+ }
+ return drop(self, num);
+ }
+
//--------------------------------------------------------------------------
// each
@@ -4535,6 +4617,23 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return DefaultGroovyMethods.groupBy(Arrays.asList(self), closure);
}
+ /**
+ * Sorts all array members into groups determined by the supplied mapping function.
+ * A "fat-free" variant of {@link #groupBy(Object[], Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 4, 5, 6]
+ * assert [1: [1, 3, 5], 0: [2, 4, 6]] == nums.groupBy(n -> n % 2)
+ * </pre>
+ *
+ * @param self an array to group
+ * @param function a function mapping entries on keys
+ * @return a new Map grouped by keys
+ * @since 6.0.0
+ */
+ public static <K, T> Map<K, List<T>> groupBy(T[] self, Function<? super T, ? extends K> function) {
+ return DefaultGroovyMethods.groupBy(Arrays.asList(self), function);
+ }
+
/**
* Sorts all array members into (sub)groups determined by the supplied
* mapping closures as per the Iterable variant of this method.
@@ -9200,6 +9299,24 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return DefaultGroovyMethods.split(closure, accept, reject, new ArrayIterator<>(self));
}
+ /**
+ * Splits all array items into two collections based on the predicate.
+ * A "fat-free" variant of {@link #split(Object[], Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 4]
+ * assert [[2, 4], [1, 3]] == nums.split(n -> n % 2 == 0)
+ * </pre>
+ *
+ * @param self an array
+ * @param predicate a predicate used to determine the target collection
+ * @return a List whose first item is the accepted values and whose second item is the rejected values
+ * @since 6.0.0
+ */
+ public static <T> Collection<Collection<T>> split(T[] self, Predicate<? super T> predicate) {
+ List<T> accept = new ArrayList<>(), reject = new ArrayList<>();
+ return DefaultGroovyMethods.split(predicate, accept, reject, new ArrayIterator<>(self));
+ }
+
//--------------------------------------------------------------------------
// sum
@@ -10070,6 +10187,32 @@ public class ArrayGroovyMethods extends DefaultGroovyMethodsSupport {
return take(self, num);
}
+ /**
+ * Returns the longest prefix of an array where each element passes the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(Object[], Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * Integer[] nums = [1, 2, 3, 0, 4]
+ * assert nums.takeWhile(n -> n < 3).toList() == [1, 2]
+ * </pre>
+ *
+ * @param self the original array
+ * @param condition the predicate that must evaluate to true to continue taking elements
+ * @return a prefix of the given array where each element passes the given predicate
+ * @since 6.0.0
+ */
+ public static <T> T[] takeWhile(T[] self, Predicate<? super T> condition) {
+ int num = 0;
+ while (num < self.length) {
+ T value = self[num];
+ if (condition.test(value)) {
+ num += 1;
+ } else {
+ break;
+ }
+ }
+ return take(self, num);
+ }
+
//--------------------------------------------------------------------------
// toList
diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index 412e125295..06baf88b22 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -3317,6 +3317,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collectMany(self, new ArrayList<>(), projection);
}
+ /**
+ * Projects each item from a source Iterable to a collection and concatenates
+ * (flattens) the resulting collections into a single list. A "fat-free" variant of
+ * {@link #collectMany(Iterable, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * def nums = 1..10
+ * def squaresAndCubesOfEvens = nums.collectMany(n -> n % 2 ? [] : [n**2, n**3])
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param projection a projecting function returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @since 6.0.0
+ */
+ public static <T, E> List<T> collectMany(Iterable<E> self, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
+ }
+
/**
* Flattens an iterable of collections into a list.
*
@@ -3358,6 +3377,26 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collectMany(self.iterator(), collector, projection);
}
+ /**
+ * Projects each item from a source collection to a result collection and concatenates
+ * (flattens) the resulting collections adding them into the <code>collector</code>.
+ * A "fat-free" variant of {@link #collectMany(Iterable, Collection, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * def animals = ['CAT', 'DOG', 'ELEPHANT']
+ * def smallAnimals = animals.collectMany(['ant', 'bee'], a -> a.size() > 3 ? [] : [a.toLowerCase()])
+ * assert smallAnimals == ['ant', 'bee', 'cat', 'dog']
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting function returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) into it
+ * @since 6.0.0
+ */
+ public static <T, E, C extends Collection<T>> C collectMany(Iterable<E> self, C collector, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return collectMany(self.iterator(), collector, projection);
+ }
+
/**
* Projects each item from a source map to a result collection and concatenates (flattens) the resulting
* collections adding them into the <code>collector</code>.
@@ -3382,6 +3421,30 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collector;
}
+ /**
+ * Projects each entry from a source map to a result collection and concatenates
+ * (flattens) the resulting collections adding them into the <code>collector</code>.
+ * A "fat-free" variant of {@link #collectMany(Map, Collection, Closure)} accepting a {@link BiFunction}.
+ * <pre class="language-groovy groovyTestCase">
+ * def map = [bread: 3, milk: 5, butter: 2]
+ * def result = map.collectMany(['x'], (k, v) -> k.startsWith('b') ? k.toList() : [])
+ * assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
+ * </pre>
+ *
+ * @param self a map
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting function returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) to it
+ * @since 6.0.0
+ */
+ public static <T, K, V, C extends Collection<T>> C collectMany(Map<K, V> self, C collector, BiFunction<? super K, ? super V, ? extends Collection<? extends T>> projection) {
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ var items = projection.apply(entry.getKey(), entry.getValue());
+ if (items != null && !items.isEmpty()) collector.addAll(items);
+ }
+ return collector;
+ }
+
/**
* Projects each item from a source map to a result collection and concatenates (flattens) the resulting
* collections adding them into a collection.
@@ -3401,6 +3464,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collectMany(self, new ArrayList<>(), projection);
}
+ /**
+ * Projects each entry from a source map to a result collection and concatenates
+ * (flattens) the resulting collections into a single list. A "fat-free" variant of
+ * {@link #collectMany(Map, Closure)} accepting a {@link BiFunction}.
+ * <pre class="language-groovy groovyTestCase">
+ * def map = [bread: 3, milk: 5, butter: 2]
+ * def result = map.collectMany((k, v) -> k.startsWith('b') ? k.toList() : [])
+ * assert result == ['b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
+ * </pre>
+ *
+ * @param self a map
+ * @param projection a projecting function returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @since 6.0.0
+ */
+ public static <T, K, V> List<T> collectMany(Map<K, V> self, BiFunction<? super K, ? super V, ? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
+ }
+
/**
* Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
* <p>
@@ -3436,6 +3518,31 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collector;
}
+ /**
+ * Projects each item from a source iterator to a collection and concatenates
+ * (flattens) the resulting collections adding them into the <code>collector</code>.
+ * A "fat-free" variant of {@link #collectMany(Iterator, Collection, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
+ * def squaresAndCubesOfEvens = numsIter.collectMany([], n -> n % 2 == 0 ? [n**2, n**3] : [])
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
+ * </pre>
+ *
+ * @param self an iterator
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting function returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) to it
+ * @since 6.0.0
+ */
+ public static <T, E, C extends Collection<T>> C collectMany(Iterator<E> self, C collector, Function<? super E, ? extends Collection<? extends T>> projection) {
+ while (self.hasNext()) {
+ E element = self.next();
+ var items = projection.apply(element);
+ if (items != null) collector.addAll(items);
+ }
+ return collector;
+ }
+
/**
* Iterates through the elements produced by projecting and flattening the elements from a source iterator.
* <p>
@@ -3467,6 +3574,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return new CollectManyIterator<>(self, projection);
}
+ /**
+ * Iterates lazily through the elements produced by projecting and flattening the
+ * elements from a source iterator. A "fat-free" variant of
+ * {@link #collectingMany(Iterator, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
+ * def squaresAndCubesOfEvens = numsIter.collectingMany(n -> n % 2 == 0 ? [n**2, n**3] : []).collect()
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
+ * </pre>
+ *
+ * @param self a source iterator
+ * @param projection a projecting function returning a collection of items
+ * @return an iterator of the projected collections flattened
+ * @since 6.0.0
+ */
+ public static <T, E> Iterator<T> collectingMany(Iterator<E> self, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return new CollectManyFunctionIterator<>(self, projection);
+ }
+
private static final class CollectManyIterator<E, T> implements Iterator<T> {
private final Iterator<E> source;
private final Closure<? extends Collection<? extends T>> transform;
@@ -3511,6 +3637,50 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
}
+ private static final class CollectManyFunctionIterator<E, T> implements Iterator<T> {
+ private final Iterator<E> source;
+ private final Function<? super E, ? extends Collection<? extends T>> transform;
+ private final Queue<T> buffer = new LinkedList<>();
+ private boolean ready = false;
+
+ private CollectManyFunctionIterator(Iterator<E> source, Function<? super E, ? extends Collection<? extends T>> transform) {
+ this.source = source;
+ this.transform = transform;
+ advance();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return ready;
+ }
+
+ @Override
+ public T next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException("CollectManyFunctionIterator has been exhausted and contains no more elements");
+ }
+ T result = buffer.poll();
+ ready = !buffer.isEmpty();
+ advance();
+ return result;
+ }
+
+ private void advance() {
+ while (!ready && source.hasNext()) {
+ Collection<? extends T> result = transform.apply(source.next());
+ if (result != null) {
+ buffer.addAll(result);
+ }
+ ready = !buffer.isEmpty();
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/**
* Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
* <p>
@@ -3530,6 +3700,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return collectMany(self, new ArrayList<>(), projection);
}
+ /**
+ * Projects each item from a source iterator to a collection and concatenates
+ * (flattens) the resulting collections into a single list. A "fat-free" variant of
+ * {@link #collectMany(Iterator, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
+ * def squaresAndCubesOfEvens = numsIter.collectMany(n -> n % 2 ? [] : [n**2, n**3])
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
+ * </pre>
+ *
+ * @param self an iterator
+ * @param projection a projecting function returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @since 6.0.0
+ */
+ public static <T, E> List<T> collectMany(Iterator<E> self, Function<? super E, ? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
+ }
+
/**
* Flattens an iterator of collections into a single list.
* <p>
@@ -4084,6 +4273,23 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return countBy(self.iterator(), closure);
}
+ /**
+ * Sorts all collection members into groups determined by the supplied mapping
+ * function and counts the group size. A "fat-free" variant of
+ * {@link #countBy(Iterable, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [0: 2, 1: 3] == [1, 2, 3, 4, 5].countBy(n -> n % 2)
+ * </pre>
+ *
+ * @param self a collection to group and count
+ * @param function a function mapping items to the frequency keys
+ * @return a new Map grouped by keys with frequency counts
+ * @since 6.0.0
+ */
+ public static <K, E> Map<K, Integer> countBy(Iterable<E> self, Function<? super E, ? extends K> function) {
+ return countBy(self.iterator(), function);
+ }
+
/**
* Creates a multiset-like map of the collection members.
* <p>
@@ -4122,6 +4328,28 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return answer;
}
+ /**
+ * Sorts all iterator items into groups determined by the supplied mapping
+ * function and counts the group size. A "fat-free" variant of
+ * {@link #countBy(Iterator, Closure)} accepting a {@link Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [1: 2, 0: 1] == [1, 2, 2, 2, 3].toSet().iterator().countBy(n -> n % 2)
+ * </pre>
+ *
+ * @param self an iterator to group and count
+ * @param function a function mapping items to the frequency keys
+ * @return a new Map grouped by keys with frequency counts
+ * @since 6.0.0
+ */
+ public static <K, E> Map<K, Integer> countBy(Iterator<E> self, Function<? super E, ? extends K> function) {
+ Map<K, Integer> answer = new LinkedHashMap<>();
+ while (self.hasNext()) {
+ K value = function.apply(self.next());
+ countAnswer(answer, value);
+ }
+ return answer;
+ }
+
/**
* Creates a multiset-like map of the iterator members.
* <p>
@@ -4161,6 +4389,27 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return answer;
}
+ /**
+ * Groups the members of a map into groups determined by the supplied mapping
+ * function and counts the frequency of the created groups. A "fat-free" variant of
+ * {@link #countBy(Map, Closure)} accepting a {@link BiFunction}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [0: 2, 1: 3] == [a: 1, b: 2, c: 3, d: 4, e: 5].countBy((k, v) -> v % 2)
+ * </pre>
+ *
+ * @param self a map to group and count
+ * @param function a function mapping entries to frequency count keys
+ * @return a new Map grouped by keys with frequency counts
+ * @since 6.0.0
+ */
+ public static <K, U, V> Map<K, Integer> countBy(Map<U, V> self, BiFunction<? super U, ? super V, ? extends K> function) {
+ Map<K, Integer> answer = new LinkedHashMap<>();
+ for (Map.Entry<U, V> entry : self.entrySet()) {
+ countAnswer(answer, function.apply(entry.getKey(), entry.getValue()));
+ }
+ return answer;
+ }
+
private static <T> void countAnswer(final Map<T, Integer> answer, T mappedKey) {
Integer current = answer.get(mappedKey);
@@ -4815,6 +5064,22 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return (SortedSet<T>) dropWhile((Iterable<T>) self, condition);
}
+ /**
+ * Returns a suffix of a SortedSet where elements are dropped from the front while the predicate is satisfied.
+ * A "fat-free" variant of {@link #dropWhile(SortedSet, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert ([1, 2, 3] as SortedSet).dropWhile(n -> n < 3).toList() == [3]
+ * </pre>
+ *
+ * @param self the original SortedSet
+ * @param condition the predicate that must evaluate to true to continue dropping elements
+ * @return the shortest suffix of the given SortedSet such that its first element does not pass the given predicate
+ * @since 6.0.0
+ */
+ public static <T> SortedSet<T> dropWhile(SortedSet<T> self, Predicate<? super T> condition) {
+ return (SortedSet<T>) dropWhile((Iterable<T>) self, condition);
+ }
+
/**
* Returns a suffix of this List where elements are dropped from the front
* while the given Closure evaluates to true.
@@ -4847,6 +5112,30 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return drop(self, num);
}
+ /**
+ * Returns a suffix of a List where elements are dropped from the front while the predicate is satisfied.
+ * A "fat-free" variant of {@link #dropWhile(List, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [1, 2, 3, 0, 4].dropWhile(n -> n < 3) == [3, 0, 4]
+ * </pre>
+ *
+ * @param self the original list
+ * @param condition the predicate that must evaluate to true to continue dropping elements
+ * @return the shortest suffix of the given List such that its first element does not pass the given predicate
+ * @since 6.0.0
+ */
+ public static <T> List<T> dropWhile(List<T> self, Predicate<? super T> condition) {
+ int num = 0;
+ for (T value : self) {
+ if (condition.test(value)) {
+ num += 1;
+ } else {
+ break;
+ }
+ }
+ return drop(self, num);
+ }
+
/**
* Returns a suffix of this Iterable where elements are dropped from the front
* while the given closure evaluates to true.
@@ -4872,6 +5161,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return result;
}
+ /**
+ * Returns a suffix of an Iterable where elements are dropped from the front while the predicate is satisfied.
+ * A "fat-free" variant of {@link #dropWhile(Iterable, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert (1..5).dropWhile(n -> n < 3) == [3, 4, 5]
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param condition the predicate that must evaluate to true to continue dropping elements
+ * @return the shortest suffix of the given Iterable such that its first element does not pass the given predicate
+ * @since 6.0.0
+ */
+ public static <T> Collection<T> dropWhile(Iterable<T> self, Predicate<? super T> condition) {
+ Collection<T> selfCol = self instanceof Collection ? (Collection<T>) self : toList(self);
+ Collection<T> result = createSimilarCollection(selfCol);
+ addAll(result, dropWhile(self.iterator(), condition));
+ return result;
+ }
+
/**
* Create a suffix of the given Map by dropping as many entries as possible from the
* front of the original Map such that calling the given closure condition evaluates to
@@ -4906,6 +5214,31 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return ret;
}
+ /**
+ * Returns a new map containing the entries from the map after dropping the leading entries that satisfy the predicate.
+ * A "fat-free" variant of {@link #dropWhile(Map, Closure)} accepting a {@link BiPredicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [a: 1, b: 2, c: 3].dropWhile((k, v) -> v < 3) == [c: 3]
+ * </pre>
+ *
+ * @param self the original map
+ * @param condition the predicate on entry key and value that must evaluate to true to continue dropping entries
+ * @return the shortest suffix of the given map whose first entry does not pass the given predicate
+ * @since 6.0.0
+ */
+ public static <K, V> Map<K, V> dropWhile(Map<K, V> self, BiPredicate<? super K, ? super V> condition) {
+ if (self.isEmpty()) {
+ return createSimilarMap(self);
+ }
+ Map<K, V> ret = createSimilarMap(self);
+ boolean dropping = true;
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (dropping && !condition.test(entry.getKey(), entry.getValue())) dropping = false;
+ if (!dropping) ret.put(entry.getKey(), entry.getValue());
+ }
+ return ret;
+ }
+
/**
* Creates an Iterator that returns a suffix of the elements from an original Iterator. As many elements
* as possible are dropped from the front of the original Iterator such that calling the given closure
@@ -4928,13 +5261,33 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return new DropWhileIterator<>(self, condition);
}
+ /**
+ * Creates an Iterator that returns the remaining items after dropping a prefix of elements that satisfy the predicate.
+ * A "fat-free" variant of {@link #dropWhile(Iterator, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [1, 2, 3, 0, 4].iterator().dropWhile(n -> n < 3).toList() == [3, 0, 4]
+ * </pre>
+ *
+ * @param self the Iterator
+ * @param condition the predicate that must evaluate to true to continue dropping elements
+ * @return an Iterator with the elements remaining after dropping the longest prefix passing the given predicate
+ * @since 6.0.0
+ */
+ public static <T> Iterator<T> dropWhile(Iterator<T> self, Predicate<? super T> condition) {
+ return new DropWhileIterator<>(self, condition);
+ }
+
private static final class DropWhileIterator<E> implements Iterator<E> {
private final Iterator<E> delegate;
- private final Closure condition;
+ private final Predicate<? super E> condition;
private boolean buffering = false;
private E buffer = null;
private DropWhileIterator(Iterator<E> delegate, Closure condition) {
+ this(delegate, toPredicate(condition));
+ }
+
+ private DropWhileIterator(Iterator<E> delegate, Predicate<? super E> condition) {
this.delegate = delegate;
this.condition = condition;
prepare();
@@ -4968,10 +5321,9 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
private void prepare() {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
while (delegate.hasNext()) {
E next = delegate.next();
- if (!bcw.call(next)) {
+ if (!condition.test(next)) {
buffer = next;
buffering = true;
break;
@@ -8843,6 +9195,29 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return answer;
}
+ /**
+ * Groups the members of a map into sub-maps determined by the supplied mapping
+ * function. A "fat-free" variant of {@link #groupBy(Map, Closure)} accepting a {@link BiFunction}.
+ * <pre class="language-groovy groovyTestCase">
+ * def result = [a: 1, b: 2, c: 3, d: 4].groupBy((k, v) -> v % 2)
+ * assert result == [1: [a: 1, c: 3], 0: [b: 2, d: 4]]
+ * </pre>
+ *
+ * @param self a map to group
+ * @param function a function mapping entries on keys
+ * @return a new Map grouped by keys
+ * @since 6.0.0
+ */
+ public static <G, K, V> Map<G, Map<K, V>> groupBy(Map<K, V> self, BiFunction<? super K, ? super V, ? extends G> function) {
+ final Map<G, Map<K, V>> answer = new LinkedHashMap<>();
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ G key = function.apply(entry.getKey(), entry.getValue());
+ Map<K, V> target = answer.computeIfAbsent(key, k -> createSimilarMap(self));
+ target.put(entry.getKey(), entry.getValue());
+ }
+ return answer;
+ }
+
/**
* Groups the members of a map into sub maps determined by the supplied
* mapping closures. Each closure will be passed a Map.Entry or key and
@@ -15249,6 +15624,25 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return split(closure, accept, reject, iter);
}
+ /**
+ * Splits all items into two collections based on the predicate.
+ * A "fat-free" variant of {@link #split(Collection, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [[2, 4], [1, 3]] == [1, 2, 3, 4].split(n -> n % 2 == 0)
+ * </pre>
+ *
+ * @param self a Collection of values
+ * @param predicate a predicate used to determine the target collection
+ * @return a List whose first item is the accepted values and whose second item is the rejected values
+ * @since 6.0.0
+ */
+ public static <T> Collection<Collection<T>> split(Collection<T> self, Predicate<? super T> predicate) {
+ Collection<T> accept = createSimilarCollection(self);
+ Collection<T> reject = createSimilarCollection(self);
+ Iterator<T> iter = self.iterator();
+ return split(predicate, accept, reject, iter);
+ }
+
static <T> Collection<Collection<T>> split(Closure closure, Collection<T> accept, Collection<T> reject, Iterator<T> iter) {
List<Collection<T>> answer = new ArrayList<>();
BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
@@ -15265,6 +15659,21 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return answer;
}
+ static <T> Collection<Collection<T>> split(Predicate<? super T> predicate, Collection<T> accept, Collection<T> reject, Iterator<T> iter) {
+ List<Collection<T>> answer = new ArrayList<>();
+ while (iter.hasNext()) {
+ T value = iter.next();
+ if (predicate.test(value)) {
+ accept.add(value);
+ } else {
+ reject.add(value);
+ }
+ }
+ answer.add(accept);
+ answer.add(reject);
+ return answer;
+ }
+
/**
* Splits all items into two collections based on the closure condition.
* The first list contains all items which match the closure expression.
@@ -15283,6 +15692,23 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return (List<List<T>>) (List<?>) split((Collection<T>) self, closure);
}
+ /**
+ * Splits all items into two lists based on the predicate.
+ * A "fat-free" variant of {@link #split(List, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [[2, 4], [1, 3]] == [1, 2, 3, 4].split(n -> n % 2 == 0)
+ * </pre>
+ *
+ * @param self a List of values
+ * @param predicate a predicate used to determine the target list
+ * @return a List whose first item is the accepted values and whose second item is the rejected values
+ * @since 6.0.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> List<List<T>> split(List<T> self, Predicate<? super T> predicate) {
+ return (List<List<T>>) (List<?>) split((Collection<T>) self, predicate);
+ }
+
/**
* Splits all items into two collections based on the closure condition.
* The first list contains all items which match the closure expression.
@@ -15301,6 +15727,23 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return (List<Set<T>>) (List<?>) split((Collection<T>) self, closure);
}
+ /**
+ * Splits all items into two sets based on the predicate.
+ * A "fat-free" variant of {@link #split(Set, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [[2, 4], [1, 3]] == ([1, 2, 3, 4] as Set).split(n -> n % 2 == 0)*.toList()
+ * </pre>
+ *
+ * @param self a Set of values
+ * @param predicate a predicate used to determine the target set
+ * @return a List whose first item is the accepted values and whose second item is the rejected values
+ * @since 6.0.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> List<Set<T>> split(Set<T> self, Predicate<? super T> predicate) {
+ return (List<Set<T>>) (List<?>) split((Collection<T>) self, predicate);
+ }
+
//--------------------------------------------------------------------------
// spread
@@ -16188,6 +16631,30 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return take(self, num);
}
+ /**
+ * Returns the longest prefix of a List where each element passes the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(List, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [1, 2, 3, 0, 4].takeWhile(n -> n < 3) == [1, 2]
+ * </pre>
+ *
+ * @param self the original list
+ * @param condition the predicate that must evaluate to true to continue taking elements
+ * @return a prefix of the given list where each element passes the given predicate
+ * @since 6.0.0
+ */
+ public static <T> List<T> takeWhile(List<T> self, Predicate<? super T> condition) {
+ int num = 0;
+ for (T value : self) {
+ if (condition.test(value)) {
+ num += 1;
+ } else {
+ break;
+ }
+ }
+ return take(self, num);
+ }
+
/**
* Returns a Collection containing the longest prefix of the elements from this Iterable
* where each element passed to the given closure evaluates to true.
@@ -16213,6 +16680,24 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return result;
}
+ /**
+ * Returns the longest prefix of an Iterable where each element passes the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(Iterable, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert (1..5).takeWhile(n -> n < 3) == [1, 2]
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param condition the predicate that must evaluate to true to continue taking elements
+ * @return a prefix of the given Iterable where each element passes the given predicate
+ * @since 6.0.0
+ */
+ public static <T> Collection<T> takeWhile(Iterable<T> self, Predicate<? super T> condition) {
+ Collection<T> result = createSimilarCollection(self);
+ addAll(result, takeWhile(self.iterator(), condition));
+ return result;
+ }
+
/**
* Returns the longest prefix of this SortedSet where each element
* passed to the given closure condition evaluates to true.
@@ -16236,6 +16721,22 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return (SortedSet<T>) takeWhile((Iterable<T>) self, condition);
}
+ /**
+ * Returns the longest prefix of a SortedSet where each element passes the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(SortedSet, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert ([1, 2, 3] as SortedSet).takeWhile(n -> n < 3).toList() == [1, 2]
+ * </pre>
+ *
+ * @param self the original SortedSet
+ * @param condition the predicate that must evaluate to true to continue taking elements
+ * @return a prefix of the given SortedSet where each element passes the given predicate
+ * @since 6.0.0
+ */
+ public static <T> SortedSet<T> takeWhile(SortedSet<T> self, Predicate<? super T> condition) {
+ return (SortedSet<T>) takeWhile((Iterable<T>) self, condition);
+ }
+
/**
* Returns the longest prefix of this Map where each entry (or key/value pair) when
* passed to the given closure evaluates to true.
@@ -16268,6 +16769,30 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return ret;
}
+ /**
+ * Returns a new map containing the first entries from the map that satisfy the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(Map, Closure)} accepting a {@link BiPredicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [a: 1, b: 2, c: 3].takeWhile((k, v) -> v < 3) == [a: 1, b: 2]
+ * </pre>
+ *
+ * @param self the original map
+ * @param condition the predicate on entry key and value that must evaluate to true to continue taking entries
+ * @return a prefix of the given map whose entries all pass the given predicate
+ * @since 6.0.0
+ */
+ public static <K, V> Map<K, V> takeWhile(Map<K, V> self, BiPredicate<? super K, ? super V> condition) {
+ if (self.isEmpty()) {
+ return createSimilarMap(self);
+ }
+ Map<K, V> ret = createSimilarMap(self);
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (!condition.test(entry.getKey(), entry.getValue())) break;
+ ret.put(entry.getKey(), entry.getValue());
+ }
+ return ret;
+ }
+
/**
* Returns the longest prefix of elements in this iterator where
* each element passed to the given condition closure evaluates to true.
@@ -16292,15 +16817,40 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
return new TakeWhileIterator<>(self, condition);
}
+ /**
+ * Returns the longest prefix of elements in this iterator where each element passes the given predicate.
+ * A "fat-free" variant of {@link #takeWhile(Iterator, Closure)} accepting a {@link Predicate}.
+ * <pre class="language-groovy groovyTestCase">
+ * assert [1, 2, 3, 0, 4].iterator().takeWhile(n -> n < 3).toList() == [1, 2]
+ * </pre>
+ *
+ * @param self the Iterator
+ * @param condition the predicate that must evaluate to true to continue taking elements
+ * @return an Iterator with the longest prefix of elements passing the given predicate
+ * @since 6.0.0
+ */
+ public static <T> Iterator<T> takeWhile(Iterator<T> self, Predicate<? super T> condition) {
+ return new TakeWhileIterator<>(self, condition);
+ }
+
+ private static Predicate<Object> toPredicate(Closure<?> condition) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
+ return value -> bcw.call(value);
+ }
+
private static final class TakeWhileIterator<E> implements Iterator<E> {
private final Iterator<E> delegate;
- private final BooleanClosureWrapper condition;
+ private final Predicate<? super E> condition;
private boolean exhausted;
private E next;
private TakeWhileIterator(Iterator<E> delegate, Closure condition) {
+ this(delegate, toPredicate(condition));
+ }
+
+ private TakeWhileIterator(Iterator<E> delegate, Predicate<? super E> condition) {
this.delegate = delegate;
- this.condition = new BooleanClosureWrapper(condition);
+ this.condition = condition;
advance();
}
@@ -16319,15 +16869,15 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
@Override
public void remove() {
- if (exhausted) throw new NoSuchElementException();
- delegate.remove();
+ // unsupported: advance() prefetches the next element, so delegate.remove() would remove the wrong one
+ throw new UnsupportedOperationException();
}
private void advance() {
exhausted = !delegate.hasNext();
if (!exhausted) {
next = delegate.next();
- if (!condition.call(next)) {
+ if (!condition.test(next)) {
exhausted = true;
next = null;
}
diff --git a/src/test/groovy/org/apache/groovy/util/LambdasTest.groovy b/src/test/groovy/org/apache/groovy/util/LambdasTest.groovy
index 175e5e93cb..17154b65b1 100644
--- a/src/test/groovy/org/apache/groovy/util/LambdasTest.groovy
+++ b/src/test/groovy/org/apache/groovy/util/LambdasTest.groovy
@@ -232,6 +232,60 @@ class LambdasTest {
assert CompileStaticUsage.tripledViaStream(['a', 'b']) == ['aaa', 'bbb']
}
+ @Test
+ void fatFreeGroupAMatchClosureVariants() {
+ Function<Integer, List<Integer>> pair = n -> [n, n * 10]
+ assert [1, 2, 3].collectMany(pair) == [1, 2, 3].collectMany { [it, it * 10] }
+ assert [1, 2, 3].iterator().collectMany(pair).toList() == [1, 10, 2, 20, 3, 30]
+ assert [1, 2, 3].iterator().collectingMany(pair).toList() == [1, 10, 2, 20, 3, 30]
+
+ Function<Integer, Integer> parity = n -> n % 2
+ assert [1, 2, 3, 4, 5].countBy(parity) == [1, 2, 3, 4, 5].countBy { it % 2 }
+ assert [1, 2, 3, 4, 5, 6].groupBy(parity) == [1, 2, 3, 4, 5, 6].groupBy { it % 2 }
+
+ Predicate<Integer> isEven = n -> n % 2 == 0
+ assert [1, 2, 3, 4].split(isEven) == [1, 2, 3, 4].split { it % 2 == 0 }
+
+ Predicate<Integer> lessThan3 = n -> n < 3
+ assert [1, 2, 3, 0, 4].takeWhile(lessThan3) == [1, 2, 3, 0, 4].takeWhile { it < 3 }
+ assert [1, 2, 3, 0, 4].dropWhile(lessThan3) == [1, 2, 3, 0, 4].dropWhile { it < 3 }
+ assert [1, 2, 3, 0, 4].iterator().takeWhile(lessThan3).toList() == [1, 2]
+ assert [1, 2, 3, 0, 4].iterator().dropWhile(lessThan3).toList() == [3, 0, 4]
+ }
+
+ @Test
+ void fatFreeGroupAMapVariants() {
+ BiFunction<String, Integer, Integer> valueParity = (k, v) -> v % 2
+ assert [a: 1, b: 2, c: 3].countBy(valueParity) == [a: 1, b: 2, c: 3].countBy { k, v -> v % 2 }
+ assert [a: 1, b: 2, c: 3].groupBy(valueParity) == [a: 1, b: 2, c: 3].groupBy { k, v -> v % 2 }
+ assert [a: 1, b: 2, c: 3].collectMany((String k, Integer v) -> v < 3 ? [k] : []) == ['a', 'b']
+
+ BiPredicate<String, Integer> valueLessThan3 = (k, v) -> v < 3
+ assert [a: 1, b: 2, c: 3].takeWhile(valueLessThan3) == [a: 1, b: 2]
+ assert [a: 1, b: 2, c: 3].dropWhile(valueLessThan3) == [c: 3]
+ }
+
+ @Test
+ void fatFreeGroupAArrayVariants() {
+ Integer[] nums = [1, 2, 3, 4, 5, 6]
+ Function<Integer, Integer> parity = n -> n % 2
+ assert nums.countBy(parity) == [1: 3, 0: 3]
+ assert nums.groupBy(parity) == [1: [1, 3, 5], 0: [2, 4, 6]]
+ assert nums.collectMany(n -> n % 2 ? [] : [n]) == [2, 4, 6]
+
+ Predicate<Integer> isEven = n -> n % 2 == 0
+ assert nums.split(isEven) == [[2, 4, 6], [1, 3, 5]]
+ Predicate<Integer> lessThan3 = n -> n < 3
+ assert nums.takeWhile(lessThan3).toList() == [1, 2]
+ assert nums.dropWhile(lessThan3).toList() == [3, 4, 5, 6]
+ }
+
+ @Test
+ void fatFreeGroupAMethodReferenceUnderCompileStatic() {
+ // method reference selects the new countBy(Iterable, Function) twin under @CompileStatic (GROOVY-12214)
+ assert CompileStaticUsage.countByLength(['a', 'bb', 'cc', 'ddd']) == [1: 1, 2: 2, 3: 1]
+ }
+
@CompileStatic
static class CompileStaticUsage {
static List<Integer> evensViaStream(List<Integer> input) {
@@ -243,5 +297,9 @@ class LambdasTest {
BiFunction<String, Integer, String> repeat = (s, n) -> s * n
input.stream().map(curryWith(repeat, 3)).toList()
}
+
+ static Map<Integer, Integer> countByLength(List<String> input) {
+ input.countBy(String::length)
+ }
}
}