You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2023/08/02 17:17:48 UTC
[groovy] branch master updated (4f41b7942e -> 32f49c3538)
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
from 4f41b7942e additional example
new 69d676c25f sort `a` methods
new 32f49c3538 GROOVY-11145: add `join()` example
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../groovy/runtime/DefaultGroovyMethods.java | 14542 ++++++++++---------
1 file changed, 7288 insertions(+), 7254 deletions(-)
[groovy] 01/02: sort `a` methods
Posted by em...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 69d676c25fe9287eb2678e11432aa63b7dc8039d
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Aug 2 12:06:16 2023 -0500
sort `a` methods
---
.../groovy/runtime/DefaultGroovyMethods.java | 14550 ++++++++++---------
1 file changed, 7294 insertions(+), 7256 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index 5e7e67bd0b..9ee4c13d01 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -222,7225 +222,7987 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
private static final BigInteger BI_LONG_MIN = BigInteger.valueOf( Long.MIN_VALUE);
private static final NumberAwareComparator<Comparable> COMPARABLE_NUMBER_AWARE_COMPARATOR = new NumberAwareComparator<>();
+ //--------------------------------------------------------------------------
+ // abs
+
/**
- * Identity check. Since == is overridden in Groovy with the meaning of equality
- * we need some fallback to check for object identity. Invoke using the
- * 'is' method, like so: <code>def same = this.is(that)</code>
+ * Gets the absolute value.
+ * <p>
+ * Note: This method is NOT called if number is a BigInteger or BigDecimal,
+ * because those classes implement a method with a better exact match.
*
- * @param self an object
- * @param other an object to compare identity with
- * @return true if self and other are both references to the same
- * instance, false otherwise
+ * @param number a Number
+ * @return the absolute value of that Number
* @since 1.0
*/
- public static boolean is(Object self, Object other) {
- return self == other;
+ public static int abs(Number number) {
+ return Math.abs(number.intValue());
}
/**
- * Allows the closure to be called for the object reference self.
- * Synonym for 'with()'.
+ * Gets the absolute value.
*
- * @param self the object to have a closure act upon
- * @param closure the closure to call on the object
- * @return result of calling the closure
- * @see #with(Object, Closure)
+ * @param number a Long
+ * @return the absolute value of that Long
* @since 1.0
*/
- public static <T,U> T identity(
- @DelegatesTo.Target("self") U self,
- @DelegatesTo(value=DelegatesTo.Target.class,
- target="self",
- strategy=Closure.DELEGATE_FIRST)
- @ClosureParams(FirstParam.class)
- Closure<T> closure) {
- return DefaultGroovyMethods.with(self, closure);
+ public static long abs(Long number) {
+ return Math.abs(number);
}
/**
- * Allows the closure to be called for the object reference self.
- * <p>
- * Any method invoked inside the closure will first be invoked on the
- * self reference. For instance, the following method calls to the append()
- * method are invoked on the StringBuilder instance:
- * <pre class="groovyTestCase">
- * def b = new StringBuilder().with {
- * append('foo')
- * append('bar')
- * return it
- * }
- * assert b.toString() == 'foobar'
- * </pre>
- * This is commonly used to simplify object creation, such as this example:
- * <pre>
- * def p = new Person().with {
- * firstName = 'John'
- * lastName = 'Doe'
- * return it
- * }
- * </pre>
- * The other typical usage, uses the self object while creating some value:
- * <pre>
- * def fullName = person.with{ "$firstName $lastName" }
- * </pre>
+ * Gets the absolute value.
*
- * @param self the object to have a closure act upon
- * @param closure the closure to call on the object
- * @return result of calling the closure
- * @see #with(Object, boolean, Closure)
- * @see #tap(Object, Closure)
- * @since 1.5.0
+ * @param number a Float
+ * @return the absolute value of that Float
+ * @since 1.0
*/
- @SuppressWarnings("unchecked")
- public static <T,U> T with(
- @DelegatesTo.Target("self") U self,
- @DelegatesTo(value=DelegatesTo.Target.class,
- target="self",
- strategy=Closure.DELEGATE_FIRST)
- @ClosureParams(FirstParam.class)
- Closure<T> closure) {
- return (T) with(self, false, (Closure<Object>)closure);
+ public static float abs(Float number) {
+ return Math.abs(number);
}
/**
- * Allows the closure to be called for the object reference self.
- * <p/>
- * Any method invoked inside the closure will first be invoked on the
- * self reference. For example, the following method calls to the append()
- * method are invoked on the StringBuilder instance and then, because
- * 'returning' is true, the self instance is returned:
- * <pre class="groovyTestCase">
- * def b = new StringBuilder().with(true) {
- * append('foo')
- * append('bar')
- * }
- * assert b.toString() == 'foobar'
- * </pre>
- * The returning parameter is commonly set to true when using with to simplify object
- * creation, such as this example:
- * <pre>
- * def p = new Person().with(true) {
- * firstName = 'John'
- * lastName = 'Doe'
- * }
- * </pre>
- * Alternatively, 'tap' is an alias for 'with(true)', so that method can be used instead.
+ * Gets the absolute value.
*
- * The other main use case for with is when returning a value calculated using self as shown here:
- * <pre>
- * def fullName = person.with(false){ "$firstName $lastName" }
- * </pre>
- * Alternatively, 'with' is an alias for 'with(false)', so the boolean parameter can be omitted instead.
+ * @param number a Double
+ * @return the absolute value of that Double
+ * @since 1.0
+ */
+ public static double abs(Double number) {
+ return Math.abs(number);
+ }
+
+ //--------------------------------------------------------------------------
+ // addAll
+
+ /**
+ * Adds all items from the iterator to the Collection.
*
- * @param self the object to have a closure act upon
- * @param returning if true, return the self object; otherwise, the result of calling the closure
- * @param closure the closure to call on the object
- * @return the self object or the result of calling the closure depending on 'returning'
- * @see #with(Object, Closure)
- * @see #tap(Object, Closure)
- * @since 2.5.0
+ * @param self the collection
+ * @param items the items to add
+ * @return true if the collection changed
*/
- public static <T,U extends T, V extends T> T with(
- @DelegatesTo.Target("self") U self,
- boolean returning,
- @DelegatesTo(value=DelegatesTo.Target.class,
- target="self",
- strategy=Closure.DELEGATE_FIRST)
- @ClosureParams(FirstParam.class)
- Closure<T> closure) {
- @SuppressWarnings("unchecked")
- final Closure<V> clonedClosure = (Closure<V>) closure.clone();
- clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
- clonedClosure.setDelegate(self);
- V result = clonedClosure.call(self);
- return returning ? self : result;
+ public static <T> boolean addAll(Collection<T> self, Iterator<? extends T> items) {
+ boolean changed = false;
+ while (items.hasNext()) {
+ T next = items.next();
+ if (self.add(next)) changed = true;
+ }
+ return changed;
}
/**
- * Allows the closure to be called for the object reference self (similar
- * to <code>with</code>) and always returns self.
- * <p>
- * Any method invoked inside the closure will first be invoked on the
- * self reference. For instance, the following method calls to the append()
- * method are invoked on the StringBuilder instance:
- * <pre>
- * def b = new StringBuilder().tap {
- * append('foo')
- * append('bar')
- * }
- * assert b.toString() == 'foobar'
- * </pre>
- * This is commonly used to simplify object creation, such as this example:
- * <pre>
- * def p = new Person().tap {
- * firstName = 'John'
- * lastName = 'Doe'
- * }
- * </pre>
+ * Adds all items from the iterable to the Collection.
*
- * @param self the object to have a closure act upon
- * @param closure the closure to call on the object
- * @return self
- * @see #with(Object, boolean, Closure)
- * @see #with(Object, Closure)
- * @since 2.5.0
+ * @param self the collection
+ * @param items the items to add
+ * @return true if the collection changed
*/
- @SuppressWarnings("unchecked")
- public static <T,U> U tap(
- @DelegatesTo.Target("self") U self,
- @DelegatesTo(value=DelegatesTo.Target.class,
- target="self",
- strategy=Closure.DELEGATE_FIRST)
- @ClosureParams(FirstParam.class)
- Closure<T> closure) {
- return (U) with(self, true, (Closure<Object>)closure);
+ public static <T> boolean addAll(Collection<T> self, Iterable<? extends T> items) {
+ boolean changed = false;
+ for (T next : items) {
+ if (self.add(next)) changed = true;
+ }
+ return changed;
}
/**
- * Allows the subscript operator to be used to lookup dynamic property values.
- * <code>bean[somePropertyNameExpression]</code>. The normal property notation
- * of groovy is neater and more concise but only works with compile-time known
- * property names.
+ * Modifies the collection by adding all the elements in the specified array
+ * to the collection. The behavior of this operation is undefined if the
+ * specified array is modified while the operation is in progress.
+ * <p>
+ * See also {@link plus} or the '+' operator if wanting to produce a new collection
+ * containing additional items but while leaving the original collection unchanged.
*
- * @param self the object to act upon
- * @param property the property name of interest
- * @return the property value
- * @since 1.0
+ * @param self a Collection to be modified
+ * @param items array containing elements to be added to this collection
+ * @return <tt>true</tt> if this collection changed as a result of the call
+ * @see Collections#addAll
+ * @since 1.7.2
*/
- public static Object getAt(Object self, String property) {
- return InvokerHelper.getProperty(self, property);
+ public static <T> boolean addAll(Collection<T> self, T[] items) {
+ return Collections.addAll(self, items);
}
/**
- * Allows the subscript operator to be used to set dynamically named property values.
- * <code>bean[somePropertyNameExpression] = foo</code>. The normal property notation
- * of groovy is neater and more concise but only works with property names which
- * are known at compile time.
+ * Modifies this list by inserting all the elements in the specified array into the
+ * list at the specified position. Shifts the
+ * element currently at that position (if any) and any subsequent
+ * elements to the right (increases their indices). The new elements
+ * will appear in this list in the order that they occur in the array.
+ * The behavior of this operation is undefined if the specified array
+ * is modified while the operation is in progress.
*
- * @param self the object to act upon
- * @param property the name of the property to set
- * @param newValue the value to set
- * @since 1.0
+ * See also <code>plus</code> for similar functionality with copy semantics, i.e. which produces a new
+ * list after adding the additional items at the specified position but leaves the original list unchanged.
+ *
+ * @param self a list to be modified
+ * @param items array containing elements to be added to this collection
+ * @param index index at which to insert the first element from the
+ * specified array
+ * @return <tt>true</tt> if this collection changed as a result of the call
+ * @see List#addAll(int, Collection)
+ * @since 1.7.2
*/
- public static void putAt(Object self, String property, Object newValue) {
- InvokerHelper.setProperty(self, property, newValue);
+ public static <T> boolean addAll(List<T> self, int index, T[] items) {
+ return self.addAll(index, Arrays.asList(items));
}
+ //--------------------------------------------------------------------------
+ // addShutdownHook
+
/**
- * Generates a detailed dump string of an object showing its class,
- * hashCode and all accessible fields.
+ * Allows the usage of addShutdownHook without getting the runtime first.
*
- * @param self an object
- * @return the dump representation
- * @since 1.0
+ * @param self the object the method is called on (ignored)
+ * @param closure the shutdown hook action
+ * @since 1.5.0
*/
- public static String dump(Object self) {
- if (self == null) {
- return "null";
- }
- StringBuilder buffer = new StringBuilder("<");
- Class<?> klass = self.getClass();
- buffer.append(klass.getName());
- buffer.append("@");
- buffer.append(Integer.toHexString(self.hashCode()));
- boolean groovyObject = self instanceof GroovyObject;
- while (klass != null) {
- for (Field field : klass.getDeclaredFields()) {
- if (Modifier.isStatic(field.getModifiers()) || (groovyObject && field.getName().equals("metaClass"))) {
- continue;
- }
- buffer.append(" ");
- buffer.append(field.getName());
- buffer.append("=");
- if (!field.canAccess(self)) { // GROOVY-9144
- if (!SystemUtil.getBooleanSafe("groovy.force.illegal.access")
- || ReflectionUtils.makeAccessibleInPrivilegedAction(field).isEmpty()) {
- buffer.append("inaccessible");
- continue;
- }
- }
- try {
- buffer.append(FormatHelper.toString(field.get(self)));
- } catch (Exception e) {
- buffer.append(e);
- }
- }
- klass = klass.getSuperclass();
- }
- buffer.append(">");
- return buffer.toString();
+ public static void addShutdownHook(Object self, Closure closure) {
+ Runtime.getRuntime().addShutdownHook(new Thread(closure));
}
+ //--------------------------------------------------------------------------
+ // and
+
/**
- * Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it
- * in a list of {@link groovy.lang.PropertyValue} objects that additionally provide
- * the value for each property of 'self'.
+ * Bitwise AND together two Numbers.
*
- * @param self the receiver object
- * @return list of {@link groovy.lang.PropertyValue} objects
- * @see groovy.util.Expando#getMetaPropertyValues()
+ * @param left a Number
+ * @param right another Number to bitwise AND
+ * @return the bitwise AND of both Numbers
* @since 1.0
*/
- public static List<PropertyValue> getMetaPropertyValues(Object self) {
- MetaClass metaClass = InvokerHelper.getMetaClass(self);
- List<MetaProperty> mps = metaClass.getProperties();
- List<PropertyValue> props = new ArrayList<>(mps.size());
- for (MetaProperty mp : mps) {
- props.add(new PropertyValue(self, mp));
- }
- return props;
+ public static Number and(Number left, Number right) {
+ return NumberMath.and(left, right);
}
/**
- * Convenience method that calls {@link #getMetaPropertyValues(java.lang.Object)}(self)
- * and provides the data in form of simple key/value pairs, i.e. without
- * type() information.
+ * Bitwise AND together two BitSets.
*
- * @param self the receiver object
- * @return meta properties as Map of key/value pairs
- * @since 1.0
+ * @param left a BitSet
+ * @param right another BitSet to bitwise AND
+ * @return the bitwise AND of both BitSets
+ * @since 1.5.0
*/
- public static Map<String, Object> getProperties(Object self) {
- List<PropertyValue> metaProps = getMetaPropertyValues(self);
- Map<String, Object> props = new LinkedHashMap<>(metaProps.size());
-
- for (PropertyValue mp : metaProps) {
- try {
- props.put(mp.getName(), mp.getValue());
- } catch (Exception e) {
- java.util.logging.Logger.getLogger(DefaultGroovyMethods.class.getName())
- .throwing(self.getClass().getName(), "getProperty(" + mp.getName() + ")", e);
- }
- }
- return props;
+ public static BitSet and(BitSet left, BitSet right) {
+ BitSet result = (BitSet) left.clone();
+ result.and(right);
+ return result;
}
/**
- * Scoped use method
+ * Logical conjunction of two boolean operators.
*
- * @param self any Object
- * @param categoryClass a category class to use
- * @param closure the closure to invoke with the category in place
- * @return the value returned from the closure
+ * @param left left operator
+ * @param right right operator
+ * @return result of logical conjunction
* @since 1.0
*/
- public static <T> T use(Object self, Class categoryClass, Closure<T> closure) {
- return GroovyCategorySupport.use(categoryClass, closure);
+ public static Boolean and(Boolean left, Boolean right) {
+ return left && Boolean.TRUE.equals(right);
}
/**
- * Extend object with category methods.
- * All methods for given class and all super classes will be added to the object.
+ * Creates a Set composed of the intersection of a Set and an Iterable. Any
+ * elements that exist in both are added to the resultant Set.
+ * <p>
+ * This operation will always create a new object for the result,
+ * while the operands remain unchanged.
*
- * @param self any Class
- * @param categoryClasses a category classes to use
- * @since 1.6.0
- */
- public static void mixin(MetaClass self, List<Class> categoryClasses) {
- MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
- }
-
- /**
- * Extend class globally with category methods.
- * All methods for given class and all super classes will be added to the class.
+ * <pre class="groovyTestCase">
+ * def a = [1,2,3,4] as Set
+ * def b = [3,4,5,6] as Set
+ * assert (a & b) == [3,4] as Set
+ * </pre>
*
- * @param self any Class
- * @param categoryClasses a category classes to use
- * @since 1.6.0
+ * By default, Groovy uses a {@link NumberAwareComparator} when determining if an
+ * element exists in both sets.
+ *
+ * @param left a Set
+ * @param right an Iterable
+ * @return a Set as an intersection of a Set and an Iterable
+ * @see #intersect(Set, Iterable)
+ * @since 5.0.0
*/
- public static void mixin(Class self, List<Class> categoryClasses) {
- mixin(getMetaClass(self), categoryClasses);
+ public static <T> Set<T> and(Set<T> left, Iterable<T> right) {
+ return intersect(left, right);
}
/**
- * Extend class globally with category methods.
+ * Creates a Set composed of the intersection of a Set and an Iterable. Any
+ * elements that exist in both iterables are added to the resultant collection.
+ * <p>
+ * This operation will always create a new object for the result,
+ * while the operands remain unchanged.
*
- * @param self any Class
- * @param categoryClass a category class to use
- * @since 1.6.0
+ * <pre class="groovyTestCase">
+ * assert [3,4] as Set == ([1,2,3,4] as Set).and([3,4,5,6], Comparator.naturalOrder())
+ * </pre>
+ *
+ * @param left a Set
+ * @param right an Iterable
+ * @param comparator a Comparator
+ * @return a Set as an intersection of a Set and an Iterable
+ * @see #intersect(Set, Iterable, Comparator)
+ * @since 5.0.0
*/
- public static void mixin(Class self, Class categoryClass) {
- mixin(getMetaClass(self), Collections.singletonList(categoryClass));
+ public static <T> Set<T> and(Set<T> left, Iterable<T> right, Comparator<? super T> comparator) {
+ return intersect(left, right, comparator);
}
/**
- * Extend class globally with category methods.
+ * Creates a SortedSet composed of the intersection of a SortedSet and an Iterable. Any
+ * elements that exist in both are added to the resultant SortedSet.
+ * <p>
+ * This operation will always create a new object for the result,
+ * while the operands remain unchanged.
*
- * @param self any Class
- * @param categoryClass a category class to use
- * @since 1.6.0
+ * <pre class="groovyTestCase">
+ * def a = [1,2,3,4] as SortedSet
+ * def b = [3,4,5,6] as Set
+ * assert (a & b) == [3,4] as SortedSet
+ * </pre>
+ *
+ * By default, Groovy uses a {@link NumberAwareComparator} when determining if an
+ * element exists in both sets.
+ *
+ * @param left a SortedSet
+ * @param right an Iterable
+ * @return a SortedSet as an intersection of a SortedSet and an Iterable
+ * @see #intersect(Set, Iterable)
+ * @since 5.0.0
*/
- public static void mixin(Class self, Class[] categoryClass) {
- mixin(getMetaClass(self), Arrays.asList(categoryClass));
+ public static <T> SortedSet<T> and(SortedSet<T> left, Iterable<T> right) {
+ return intersect(left, right);
}
/**
- * Extend class globally with category methods.
+ * Creates a SortedSet composed of the intersection of a SortedSet and an Iterable. Any
+ * elements that exist in both iterables are added to the resultant collection.
+ * <p>
+ * This operation will always create a new object for the result,
+ * while the operands remain unchanged.
*
- * @param self any Class
- * @param categoryClass a category class to use
- * @since 1.6.0
+ * <pre class="groovyTestCase">
+ * assert [3,4] as SortedSet == ([1,2,3,4] as SortedSet).and([3,4,5,6], Comparator.naturalOrder())
+ * </pre>
+ *
+ * @param left a SortedSet
+ * @param right an Iterable
+ * @param comparator a Comparator
+ * @return a SortedSet as an intersection of a SortedSet and an Iterable
+ * @see #intersect(SortedSet, Iterable, Comparator)
+ * @since 5.0.0
*/
- public static void mixin(MetaClass self, Class categoryClass) {
- mixin(self, Collections.singletonList(categoryClass));
+ public static <T> SortedSet<T> and(SortedSet<T> left, Iterable<T> right, Comparator<? super T> comparator) {
+ return intersect(left, right, comparator);
}
+ //--------------------------------------------------------------------------
+ // any
+
/**
- * Extend class globally with category methods.
+ * Iterates over the elements of a collection, and checks whether at least
+ * one element is true according to the Groovy Truth.
+ * Equivalent to self.any({element {@code ->} element})
+ * <pre class="groovyTestCase">
+ * assert [false, true].any()
+ * assert [0, 1].any()
+ * assert ![0, 0].any()
+ * </pre>
*
- * @param self any Class
- * @param categoryClass a category class to use
- * @since 1.6.0
+ * @param self the object over which we iterate
+ * @return true if any item in the collection matches the closure predicate
+ * @since 1.5.0
*/
- public static void mixin(MetaClass self, Class[] categoryClass) {
- mixin(self, Arrays.asList(categoryClass));
+ public static boolean any(Object self) {
+ BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
+ for (var iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
+ if (bmi.convertToBoolean(iter.next())) {
+ return true;
+ }
+ }
+ return false;
}
/**
- * Gets the url of the jar file/source file containing the specified class
+ * Iterates over the contents of an object or collection, and checks whether a
+ * predicate is valid for at least one element.
+ * <pre class="groovyTestCase">
+ * assert [1, 2, 3].any { it == 2 }
+ * assert ![1, 2, 3].any { it {@code >} 3 }
+ * </pre>
*
- * @param self the class
- * @return the url of the jar, {@code null} if the specified class is from JDK
- * @since 2.5.0
+ * @param self the object over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if any iteration for the object matches the closure predicate
+ * @since 1.0
*/
- public static URL getLocation(Class self) {
- CodeSource codeSource = self.getProtectionDomain().getCodeSource();
-
- return null == codeSource ? null : codeSource.getLocation();
+ public static boolean any(Object self, Closure predicate) {
+ return any(InvokerHelper.asIterator(self), predicate);
}
/**
- * Allows the usage of addShutdownHook without getting the runtime first.
+ * Iterates over the contents of an iterator, and checks whether a
+ * predicate is valid for at least one element.
+ * <pre class="groovyTestCase">
+ * assert [1, 2, 3].iterator().any { it == 2 }
+ * assert ![1, 2, 3].iterator().any { it {@code >} 3 }
+ * </pre>
*
- * @param self the object the method is called on (ignored)
- * @param closure the shutdown hook action
- * @since 1.5.0
+ * @param self the iterator over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if any iteration for the object matches the closure predicate
+ * @since 1.0
*/
- public static void addShutdownHook(Object self, Closure closure) {
- Runtime.getRuntime().addShutdownHook(new Thread(closure));
+ public static <T> boolean any(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
+ while (self.hasNext()) {
+ if (bcw.call(self.next())) {
+ return true;
+ }
+ }
+ return false;
}
/**
- * Scoped use method with list of categories.
+ * Iterates over the contents of an iterable, and checks whether a
+ * predicate is valid for at least one element.
+ * <pre class="groovyTestCase">
+ * assert [1, 2, 3].any { it == 2 }
+ * assert ![1, 2, 3].any { it {@code >} 3 }
+ * </pre>
*
- * @param self any Object
- * @param categoryClassList a list of category classes
- * @param closure the closure to invoke with the categories in place
- * @return the value returned from the closure
+ * @param self the iterable over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if any iteration for the object matches the closure predicate
* @since 1.0
*/
- public static <T> T use(Object self, List<Class> categoryClassList, Closure<T> closure) {
- return GroovyCategorySupport.use(categoryClassList, closure);
+ public static <T> boolean any(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
+ return any(self.iterator(), predicate);
}
/**
- * Allows you to use a list of categories, specifying the list as varargs.
- * <code>use(CategoryClass1, CategoryClass2) { ... }</code>
- * This method saves having to wrap the category
- * classes in a list.
+ * Iterates over the entries of a map, and checks whether a predicate is
+ * valid for at least one entry. If the
+ * closure takes one parameter then it will be passed the Map.Entry
+ * otherwise if the closure takes two parameters then it will be
+ * passed the key and the value.
+ * <pre class="groovyTestCase">
+ * assert [2:3, 4:5, 5:10].any { key, value {@code ->} key * 2 == value }
+ * assert ![2:3, 4:5, 5:10].any { entry {@code ->} entry.key == entry.value * 2 }
+ * </pre>
*
- * @param self any Object
- * @param array a list of category classes and a Closure
- * @return the value returned from the closure
- * @since 1.0
+ * @param self the map over which we iterate
+ * @param predicate the 1 or 2 arg closure predicate used for matching
+ * @return true if any entry in the map matches the closure predicate
+ * @since 1.5.0
*/
- @SuppressWarnings("unchecked")
- public static Object use(Object self, Object[] array) {
- if (array.length < 2)
- throw new IllegalArgumentException(
- "Expecting at least 2 arguments, a category class and a Closure");
- Closure closure;
- try {
- closure = (Closure) array[array.length - 1];
- } catch (ClassCastException e) {
- throw new IllegalArgumentException("Expecting a Closure to be the last argument");
- }
- List<Class> list = new ArrayList<>(array.length - 1);
- for (int i = 0; i < array.length - 1; ++i) {
- Class categoryClass;
- try {
- categoryClass = (Class) array[i];
- } catch (ClassCastException e) {
- throw new IllegalArgumentException("Expecting a Category Class for argument " + i);
+ public static <K, V> boolean any(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> predicate) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
+ for (var entry : self.entrySet()) {
+ if (bcw.callForMap(entry)) {
+ return true;
}
- list.add(categoryClass);
}
- return GroovyCategorySupport.use(list, closure);
+ return false;
}
- private static Object getClosureOwner(Closure<?> cls) {
- Object owner = cls.getOwner();
- while (owner instanceof GeneratedClosure) {
- owner = ((Closure<?>) owner).getOwner();
- }
- return owner;
- }
+ //--------------------------------------------------------------------------
+ // asBoolean
/**
- * Inspects returns the String that matches what would be typed into a
- * terminal to create this object.
+ * Coerce an object instance to a boolean value.
+ * An object is coerced to true if it's not null, to false if it is null.
*
- * @param self any Object
- * @return a String that matches what would be typed into a terminal to
- * create this object. e.g. [1, 'hello'].inspect() {@code ->} [1, 'hello']
- * @since 1.0
+ * @param object the object to coerce
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static String inspect(Object self) {
- return FormatHelper.inspect(self);
+ public static boolean asBoolean(Object object) {
+ return object != null;
}
/**
- * Provide a dynamic method invocation method which can be overloaded in
- * classes to implement dynamic proxies easily.
+ * Coerce a Boolean instance to a boolean value.
+ * <pre class="groovyTestCase">
+ * // you can omit ".asBoolean()"
+ * assert Boolean.TRUE.asBoolean()
+ * assert !Boolean.FALSE.asBoolean()
+ * </pre>
*
- * @param object any Object
- * @param method the name of the method to call
- * @param arguments the arguments to use
- * @return the result of the method call
- * @since 1.0
+ * @since 1.7.0
*/
- public static Object invokeMethod(Object object, String method, Object arguments) {
- return InvokerHelper.invokeMethod(object, method, arguments);
+ public static boolean asBoolean(Boolean bool) {
+ return bool != null && bool.booleanValue();
}
- //--------------------------------------------------------------------------
- // print/println/printf/sprintf
-
/**
- * Print a value formatted Groovy style to self if it
- * is a Writer, otherwise to the standard output stream.
+ * Coerce an AtomicBoolean instance to a boolean value.
+ * <pre class="groovyTestCase">
+ * import java.util.concurrent.atomic.AtomicBoolean
*
- * @param self any Object
- * @param value the value to print
- * @since 1.0
+ * // you can omit ".asBoolean()"
+ * assert new AtomicBoolean(true).asBoolean()
+ * assert !new AtomicBoolean(false).asBoolean()
+ * assert !new AtomicBoolean(true).tap{set(false)}
+ * </pre>
+ *
+ * @since 5.0.0
*/
- public static void print(Object self, Object value) {
- // we won't get here if we are a PrintWriter
- if (self instanceof Writer) {
- try {
- ((Writer) self).write(FormatHelper.toString(value));
- } catch (IOException e) {
- // TODO: Should we have some unified function like PrintWriter.checkError()?
- }
- } else {
- System.out.print(FormatHelper.toString(value));
- }
+ public static boolean asBoolean(AtomicBoolean bool) {
+ return bool != null && bool.get();
}
/**
- * Print a value formatted Groovy style to the print writer.
+ * Coerce a collection instance to a boolean value.
+ * A collection is coerced to false if it's empty, and to true otherwise.
+ * <pre class="groovyTestCase">assert [1,2].asBoolean() == true</pre>
+ * <pre class="groovyTestCase">assert [].asBoolean() == false</pre>
*
- * @param self a PrintWriter
- * @param value the value to print
- * @since 1.0
+ * @param collection the collection
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void print(PrintWriter self, Object value) {
- self.print(FormatHelper.toString(value));
+ public static boolean asBoolean(Collection collection) {
+ return collection != null && !collection.isEmpty();
}
/**
- * Print a value formatted Groovy style to the print stream.
+ * Coerce a map instance to a boolean value.
+ * A map is coerced to false if it's empty, and to true otherwise.
+ * <pre class="groovyTestCase">assert [:] as Boolean == false
+ * assert [a:2] as Boolean == true</pre>
*
- * @param self a PrintStream
- * @param value the value to print
- * @since 1.6.0
+ * @param map the map
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void print(PrintStream self, Object value) {
- self.print(FormatHelper.toString(value));
+ public static boolean asBoolean(Map map) {
+ return map != null && !map.isEmpty();
}
/**
- * Print a value to the standard output stream.
- * This method delegates to the owner to execute the method.
+ * Coerce an iterator instance to a boolean value.
+ * An iterator is coerced to false if there are no more elements to iterate over,
+ * and to true otherwise.
*
- * @param self a generated closure
- * @param value the value to print
- * @since 1.0
+ * @param iterator the iterator
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void print(Closure self, Object value) {
- Object owner = getClosureOwner(self);
- InvokerHelper.invokeMethod(owner, "print", new Object[]{value});
+ public static boolean asBoolean(Iterator iterator) {
+ return iterator != null && iterator.hasNext();
}
/**
- * Print to a console in interactive format.
+ * Coerce an enumeration instance to a boolean value.
+ * An enumeration is coerced to false if there are no more elements to enumerate,
+ * and to true otherwise.
*
- * @param self any Object
- * @param out the PrintWriter used for printing
- * @since 1.0
+ * @param enumeration the enumeration
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void print(Object self, PrintWriter out) {
- if (out == null) {
- out = new PrintWriter(System.out);
- }
- out.print(FormatHelper.toString(self));
+ public static boolean asBoolean(Enumeration enumeration) {
+ return enumeration != null && enumeration.hasMoreElements();
}
/**
- * Print a linebreak to the standard output stream.
+ * Coerce a character to a boolean value.
+ * A character is coerced to false if it's character value is equal to 0,
+ * and to true otherwise.
*
- * @param self any Object
- * @since 1.0
+ * @param character the character
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void println(Object self) {
- // we won't get here if we are a PrintWriter
- if (self instanceof Writer) {
- PrintWriter pw = new GroovyPrintWriter((Writer) self);
- pw.println();
- } else {
- System.out.println();
- }
+ public static boolean asBoolean(Character character) {
+ return character != null && character != 0;
}
/**
- * Print a linebreak to the standard output stream.
- * This method delegates to the owner to execute the method.
+ * Coerce a Float instance to a boolean value.
*
- * @param self a closure
- * @since 1.0
+ * @param object the Float
+ * @return {@code true} for non-zero and non-NaN values, else {@code false}
+ * @since 2.6.0
*/
- public static void println(Closure self) {
- Object owner = getClosureOwner(self);
- InvokerHelper.invokeMethod(owner, "println", InvokerHelper.EMPTY_ARGS);
+ public static boolean asBoolean(Float object) {
+ float f = object;
+ return f != 0.0f && !Float.isNaN(f);
}
/**
- * Print a value formatted Groovy style (followed by a newline) to self
- * if it is a Writer, otherwise to the standard output stream.
+ * Coerce a Double instance to a boolean value.
*
- * @param self any Object
- * @param value the value to print
- * @since 1.0
+ * @param object the Double
+ * @return {@code true} for non-zero and non-NaN values, else {@code false}
+ * @since 2.6.0
*/
- public static void println(Object self, Object value) {
- // we won't get here if we are a PrintWriter
- if (self instanceof Writer) {
- final PrintWriter pw = new GroovyPrintWriter((Writer) self);
- pw.println(value);
- } else {
- System.out.println(FormatHelper.toString(value));
- }
+ public static boolean asBoolean(Double object) {
+ double d = object;
+ return d != 0.0d && !Double.isNaN(d);
}
/**
- * Print a value formatted Groovy style (followed by a newline) to the print writer.
+ * Coerce a number to a boolean value.
+ * A number is coerced to false if its double value is equal to 0, and to true otherwise.
*
- * @param self a PrintWriter
- * @param value the value to print
- * @since 1.0
+ * @param number the number
+ * @return the boolean value
+ * @since 1.7.0
*/
- public static void println(PrintWriter self, Object value) {
- self.println(FormatHelper.toString(value));
+ public static boolean asBoolean(Number number) {
+ return number != null && number.doubleValue() != 0;
}
+ //--------------------------------------------------------------------------
+ // asChecked
+
/**
- * Print a value formatted Groovy style (followed by a newline) to the print stream.
+ * Creates a checked view of a List.
*
- * @param self any Object
- * @param value the value to print
- * @since 1.6.0
+ * @see Collections#checkedList
+ * @since 5.0.0
*/
- public static void println(PrintStream self, Object value) {
- self.println(FormatHelper.toString(value));
+ public static <T> List<T> asChecked(List<T> self, Class<T> type) {
+ return Collections.checkedList(self, type);
}
/**
- * Print a value (followed by a newline) to the standard output stream.
- * This method delegates to the owner to execute the method.
+ * Creates a checked view of a Queue.
*
- * @param self a closure
- * @param value the value to print
- * @since 1.0
+ * @see Collections#checkedQueue
+ * @since 5.0.0
*/
- public static void println(Closure self, Object value) {
- Object owner = getClosureOwner(self);
- InvokerHelper.invokeMethod(owner, "println", new Object[]{value});
+ public static <T> Queue<T> asChecked(Queue<T> self, Class<T> type) {
+ return Collections.checkedQueue(self, type);
}
/**
- * Print to a console in interactive format.
+ * Creates a checked view of a Collection.
*
- * @param self any Object
- * @param out the PrintWriter used for printing
- * @since 1.0
+ * @see Collections#checkedCollection
+ * @since 5.0.0
*/
- public static void println(Object self, PrintWriter out) {
- if (out == null) {
- out = new PrintWriter(System.out);
- }
- out.println(FormatHelper.toString(self));
+ public static <T> Collection<T> asChecked(Collection<T> self, Class<T> type) {
+ return Collections.checkedCollection(self, type);
}
/**
- * Printf to the standard output stream.
+ * Creates a checked view of a Set.
*
- * @param self any Object
- * @param format a format string
- * @param values values referenced by the format specifiers in the format string
- * @since 1.0
+ * @see Collections#checkedSet
+ * @since 5.0.0
*/
- public static void printf(Object self, String format, Object[] values) {
- if (self instanceof PrintStream)
- ((PrintStream)self).printf(format, values);
- else
- System.out.printf(format, values);
+ public static <T> Set<T> asChecked(Set<T> self, Class<T> type) {
+ return Collections.checkedSet(self, type);
}
/**
- * Printf 0 or more values to the standard output stream using a format string.
- * This method delegates to the owner to execute the method.
+ * Creates a checked view of a SortedSet.
*
- * @param self a generated closure
- * @param format a format string
- * @param values values referenced by the format specifiers in the format string
- * @since 3.0.0
+ * @see Collections#checkedSortedSet
+ * @since 5.0.0
*/
- public static void printf(Closure self, String format, Object[] values) {
- Object owner = getClosureOwner(self);
- Object[] newValues = new Object[values.length + 1];
- newValues[0] = format;
- System.arraycopy(values, 0, newValues, 1, values.length);
- InvokerHelper.invokeMethod(owner, "printf", newValues);
+ public static <T> SortedSet<T> asChecked(SortedSet<T> self, Class<T> type) {
+ return Collections.checkedSortedSet(self, type);
}
/**
- * Printf a value to the standard output stream using a format string.
- * This method delegates to the owner to execute the method.
+ * Creates a checked view of a NavigableSet.
*
- * @param self a generated closure
- * @param format a format string
- * @param value value referenced by the format specifier in the format string
- * @since 3.0.0
+ * @see Collections#checkedNavigableSet
+ * @since 5.0.0
*/
- public static void printf(Closure self, String format, Object value) {
- Object owner = getClosureOwner(self);
- Object[] newValues = new Object[2];
- newValues[0] = format;
- newValues[1] = value;
- InvokerHelper.invokeMethod(owner, "printf", newValues);
+ public static <T> NavigableSet<T> asChecked(NavigableSet<T> self, Class<T> type) {
+ return Collections.checkedNavigableSet(self, type);
}
/**
- * Prints a formatted string using the specified format string and arguments.
- * <p>
- * Examples:
- * <pre>
- * printf ( "Hello, %s!\n" , [ "world" ] as String[] )
- * printf ( "Hello, %s!\n" , [ "Groovy" ])
- * printf ( "%d + %d = %d\n" , [ 1 , 2 , 1+2 ] as Integer[] )
- * printf ( "%d + %d = %d\n" , [ 3 , 3 , 3+3 ])
+ * Creates a checked view of a Map.
*
- * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as Integer[] ) }
- * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as int[] ) }
- * ( 0x41..0x45 ).each { printf ( "-- %c\n" , [ it ] as char[] ) }
- * ( 07..011 ).each { printf ( "-- %d\n" , [ it ] as byte[] ) }
- * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as short[] ) }
- * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as long[] ) }
- * ( 7..11 ).each { printf ( "-- %5.2f\n" , [ it ] as float[] ) }
- * ( 7..11 ).each { printf ( "-- %5.2g\n" , [ it ] as double[] ) }
- * </pre>
+ * @see Collections#checkedMap
+ * @since 5.0.0
+ */
+ public static <K,V> Map<K,V> asChecked(Map<K,V> self, Class<K> keyType, Class<V> valueType) {
+ return Collections.checkedMap(self, keyType, valueType);
+ }
+
+ /**
+ * Creates a checked view of a SortedMap.
*
- * @param self any Object
- * @param format A format string
- * @param arg Argument which is referenced by the format specifiers in the format
- * string. The type of <code>arg</code> should be one of Object[], List,
- * int[], short[], byte[], char[], boolean[], long[], float[], or double[].
- * @since 1.0
+ * @see Collections#checkedSortedMap
+ * @since 5.0.0
*/
- public static void printf(Object self, String format, Object arg) {
- if (self instanceof PrintStream)
- printf((PrintStream) self, format, arg);
- else if (self instanceof Writer)
- printf((Writer) self, format, arg);
- else
- printf(System.out, format, arg);
+ public static <K,V> SortedMap<K,V> asChecked(SortedMap<K,V> self, Class<K> keyType, Class<V> valueType) {
+ return Collections.checkedSortedMap(self, keyType, valueType);
}
- private static void printf(PrintStream self, String format, Object arg) {
- self.print(sprintf(self, format, arg));
+ /**
+ * Creates a checked view of a NavigableMap.
+ *
+ * @see Collections#checkedNavigableMap
+ * @since 5.0.0
+ */
+ public static <K,V> NavigableMap<K,V> asChecked(NavigableMap<K,V> self, Class<K> keyType, Class<V> valueType) {
+ return Collections.checkedNavigableMap(self, keyType, valueType);
}
- private static void printf(Writer self, String format, Object arg) {
- try {
- self.write(sprintf(self, format, arg));
- } catch (IOException e) {
- printf(System.out, format, arg);
+ //--------------------------------------------------------------------------
+ // asCollection
+
+ /**
+ * Converts this Iterable to a Collection. Returns the original argument
+ * if it is already a Collection.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">
+ * assert new HashSet().asCollection() instanceof Collection
+ * </pre>
+ *
+ * @param self an Iterable to be converted into a Collection
+ * @return a newly created List if this Iterable is not already a Collection
+ * @since 2.4.0
+ */
+ public static <T> Collection<T> asCollection(Iterable<T> self) {
+ if (self instanceof Collection) {
+ return (Collection<T>) self;
+ } else {
+ return toList(self);
}
}
+ //--------------------------------------------------------------------------
+ // asImmutable (really toImmutable)
+
/**
- * Sprintf to a string.
+ * A convenience method for creating an immutable Map.
*
- * @param self any Object
- * @param format a format string
- * @param values values referenced by the format specifiers in the format string
- * @return the resulting formatted string
- * @since 1.5.0
+ * @param self a Map
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asImmutable(java.util.List)
+ * @see #asUnmodifiable(java.util.Map)
+ * @since 1.0
*/
- public static String sprintf(Object self, String format, Object[] values) {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- PrintStream out = new PrintStream(outputStream);
- out.printf(format, values);
- return outputStream.toString();
+ public static <K,V> Map<K,V> asImmutable(Map<K,V> self) {
+ return asUnmodifiable(new LinkedHashMap<>(self));
}
/**
- * Returns a formatted string using the specified format string and
- * arguments.
+ * A convenience method for creating an immutable SortedMap.
*
- * @param self any Object
- * @param format A format string
- * @param arg Argument which is referenced by the format specifiers in the format
- * string. The type of <code>arg</code> should be one of Object[], List,
- * int[], short[], byte[], char[], boolean[], long[], float[], or double[].
- * @return the resulting printf'd string
- * @since 1.5.0
+ * @param self a SortedMap
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asImmutable(java.util.List)
+ * @see #asUnmodifiable(java.util.SortedMap)
+ * @since 1.0
*/
- public static String sprintf(Object self, String format, Object arg) {
- if (arg instanceof Object[]) {
- return sprintf(self, format, (Object[]) arg);
- }
- if (arg instanceof List) {
- return sprintf(self, format, ((List) arg).toArray());
- }
- if (!arg.getClass().isArray()) {
- Object[] o = (Object[]) java.lang.reflect.Array.newInstance(arg.getClass(), 1);
- o[0] = arg;
- return sprintf(self, format, o);
- }
-
- Object[] ans;
- String elemType = arg.getClass().getName();
- switch (elemType) {
- case "[I":
- int[] ia = (int[]) arg;
- ans = new Integer[ia.length];
- for (int i = 0; i < ia.length; i++) {
- ans[i] = ia[i];
- }
- break;
- case "[C":
- char[] ca = (char[]) arg;
- ans = new Character[ca.length];
- for (int i = 0; i < ca.length; i++) {
- ans[i] = ca[i];
- }
- break;
- case "[Z": {
- boolean[] ba = (boolean[]) arg;
- ans = new Boolean[ba.length];
- for (int i = 0; i < ba.length; i++) {
- ans[i] = ba[i];
- }
- break;
- }
- case "[B": {
- byte[] ba = (byte[]) arg;
- ans = new Byte[ba.length];
- for (int i = 0; i < ba.length; i++) {
- ans[i] = ba[i];
- }
- break;
- }
- case "[S":
- short[] sa = (short[]) arg;
- ans = new Short[sa.length];
- for (int i = 0; i < sa.length; i++) {
- ans[i] = sa[i];
- }
- break;
- case "[F":
- float[] fa = (float[]) arg;
- ans = new Float[fa.length];
- for (int i = 0; i < fa.length; i++) {
- ans[i] = fa[i];
- }
- break;
- case "[J":
- long[] la = (long[]) arg;
- ans = new Long[la.length];
- for (int i = 0; i < la.length; i++) {
- ans[i] = la[i];
- }
- break;
- case "[D":
- double[] da = (double[]) arg;
- ans = new Double[da.length];
- for (int i = 0; i < da.length; i++) {
- ans[i] = da[i];
- }
- break;
- default:
- throw new RuntimeException("sprintf(String," + arg + ")");
- }
- return sprintf(self, format, ans);
- }
-
- //-------------------------------------------------------------------------
- // isCase/isNotCase
-
- /**
- * Method for overloading the behavior of the 'case' method in switch statements.
- * The default implementation handles arrays types but otherwise simply delegates
- * to Object#equals, but this may be overridden for other types. In this example:
- * <pre> switch( a ) {
- * case b: //some code
- * }</pre>
- * "some code" is called when <code>b.isCase( a )</code> returns
- * <code>true</code>.
- *
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return true if the switchValue is deemed to be equal to the caseValue
- * @since 1.0
- */
- public static boolean isCase(Object caseValue, Object switchValue) {
- if (caseValue.getClass().isArray()) {
- return isCase(DefaultTypeTransformation.asCollection(caseValue), switchValue);
- }
- return caseValue.equals(switchValue);
- }
+ public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K,V> self) {
+ return asUnmodifiable(new TreeMap<>(self));
+ }
/**
- * Special 'Case' implementation for Class, which allows testing
- * whether some switch value is assignable from the given case class.
- *
- * If the switch value is an object, {@code isCase} will return true if the
- * switch value is assignment compatible with the class (case value),
- * i.e. is an {@code instanceof} the class, for example:
- * <pre class="groovyTestCase">
- * def someList = []
- * switch (someList) {
- * case List:
- * assert true : 'is a list'
- * break
- * case Map:
- * assert false : 'is not a Map'
- * break
- * default:
- * assert false : 'should never get here'
- * break
- * }
- * </pre>
- *
- * If the switch value is a class, {@code isCase} will return true if the
- * switch value is assignable from the given class (case value), i.e. the case class
- * is the same as, or a superclass, or a super-interface of the switch class, for example:
+ * A convenience method for creating an immutable List.
* <pre class="groovyTestCase">
- * switch (ArrayList) {
- * case List:
- * assert true : 'is a list'
- * break
- * case Map:
- * assert false : 'is not a Map'
- * break
- * default:
- * assert false : 'should never get here'
- * break
+ * def mutable = [1,2,3]
+ * def immutable = mutable.asImmutable()
+ * try {
+ * immutable << 4
+ * assert false
+ * } catch (UnsupportedOperationException) {
+ * assert true
* }
+ * mutable << 4
+ * assert mutable.size() == 4
+ * assert immutable.size() == 3
* </pre>
*
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return true if the switchValue is deemed to be assignable from the given class
+ * @param self a List
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asUnmodifiable(java.util.List)
* @since 1.0
*/
- @SuppressWarnings("unchecked")
- public static boolean isCase(Class caseValue, Object switchValue) {
- if (switchValue instanceof Class) {
- Class val = (Class) switchValue;
- return caseValue.isAssignableFrom(val);
- }
- return caseValue.isInstance(switchValue);
+ public static <T> List<T> asImmutable(List<T> self) {
+ return asUnmodifiable(new ArrayList<>(self));
}
/**
- * 'Case' implementation for collections which tests if the 'switch'
- * operand is contained in any of the 'case' values.
- * For example:
- * <pre class="groovyTestCase">switch( 3 ) {
- * case [1,3,5]:
- * assert true
- * break
- * default:
- * assert false
- * }</pre>
+ * A convenience method for creating an immutable Set.
*
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return true if the caseValue is deemed to contain the switchValue
- * @see java.util.Collection#contains(java.lang.Object)
+ * @param self a Set
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asImmutable(java.util.List)
+ * @see #asUnmodifiable(java.util.Set)
* @since 1.0
*/
- public static boolean isCase(Collection caseValue, Object switchValue) {
- return caseValue.contains(switchValue);
+ public static <T> Set<T> asImmutable(Set<T> self) {
+ return asUnmodifiable(new LinkedHashSet<>(self));
}
/**
- * 'Case' implementation for iterable types which tests if the 'switch'
- * operand is contained in any of the 'case' values.
- * For example:
- * <pre class="groovyTestCase">Iterable it = {[1,3,5].iterator()}
- * switch( 3 ) {
- * case it:
- * assert true
- * break
- * default:
- * assert false
- * }
- *
- * //GROOVY-7919
- * assert 1 in it
- * assert 2 !in it
- * </pre>
+ * A convenience method for creating an immutable SortedSet.
*
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return true if the caseValue is deemed to contain the switchValue
- * @see #contains(Iterable,Object)
- * @since 5.0.0
+ * @param self a SortedSet
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asImmutable(java.util.List)
+ * @see #asUnmodifiable(java.util.SortedSet)
+ * @since 1.0
*/
- public static boolean isCase(Iterable caseValue, Object switchValue) {
- return contains(caseValue, switchValue);
+ public static <T> SortedSet<T> asImmutable(SortedSet<T> self) {
+ return asUnmodifiable(new TreeSet<>(self));
}
/**
- * 'Case' implementation for maps which tests the groovy truth
- * value obtained using the 'switch' operand as key.
- * For example:
- * <pre class="groovyTestCase">switch( 'foo' ) {
- * case [foo:true, bar:false]:
- * assert true
- * break
- * default:
- * assert false
- * }</pre>
+ * A convenience method for creating an immutable Collection.
*
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return the groovy truth value from caseValue corresponding to the switchValue key
- * @since 1.7.6
+ * @param self a Collection
+ * @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy
+ * @see #asImmutable(java.util.List)
+ * @see #asUnmodifiable(java.util.Collection)
+ * @since 1.5.0
*/
- public static boolean isCase(Map caseValue, Object switchValue) {
- return DefaultTypeTransformation.castToBoolean(caseValue.get(switchValue));
+ public static <T> Collection<T> asImmutable(Collection<T> self) {
+ return asUnmodifiable((Collection<T>) new ArrayList<>(self));
}
+ //--------------------------------------------------------------------------
+ // asList
+
/**
- * Special 'case' implementation for all numbers, which delegates to the
- * <code>compareTo()</code> method for comparing numbers of different
- * types.
+ * Converts this Iterable to a List. Returns the original Iterable
+ * if it is already a List.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">
+ * assert new HashSet().asList() instanceof List
+ * </pre>
*
- * @param caseValue the case value
- * @param switchValue the switch value
- * @return true if the numbers are deemed equal
- * @since 1.5.0
+ * @param self an Iterable to be converted into a List
+ * @return a newly created List if this Iterable is not already a List
+ * @since 2.2.0
*/
- public static boolean isCase(Number caseValue, Number switchValue) {
- return NumberMath.compareTo(caseValue, switchValue) == 0;
+ public static <T> List<T> asList(Iterable<T> self) {
+ if (self instanceof List) {
+ return (List<T>) self;
+ } else {
+ return toList(self);
+ }
}
- /**
- * @since 4.0.0
- */
- public static boolean isNotCase(Number caseValue, Number switchValue) {
- return !isCase(caseValue, switchValue);
- }
-
- /**
- * @since 4.0.0
- */
- public static boolean isNotCase(Object caseValue, Object switchValue) {
- return !isCase(caseValue, switchValue);
- }
+ //--------------------------------------------------------------------------
+ // asReversed
/**
+ * Creates a view list with reversed order, and the order of original list will not change.
+ * <pre class="groovyTestCase">
+ * def list = ["a", 6, true]
+ * assert list.asReversed() == [true, 6, "a"]
+ * assert list == ["a", 6, true]
+ * </pre>
+ *
+ * @param self a list
+ * @param <T> the type of element
+ * @return the reversed list
* @since 4.0.0
*/
- public static boolean isNotCase(Class<?> caseValue, Object switchValue) {
- return !isCase(caseValue, switchValue);
+ public static <T> List<T> asReversed(List<T> self) {
+ return new ReversedList<>(self);
}
/**
- * @since 4.0.0
+ * Creates a reverse order view of the set. The order of original list will not change.
+ * <pre class="groovyTestCase">
+ * TreeSet navSet = [2, 4, 1, 3] // natural order is sorted
+ * assert navSet.asReversed() == [4, 3, 2, 1] as Set
+ * </pre>
+ *
+ * @param self a NavigableSet
+ * @param <T> the type of element
+ * @return the reversed view NavigableSet
+ * @since 4.0.11
*/
- public static boolean isNotCase(Closure<?> caseValue, Object switchValue) {
- return !caseValue.isCase(switchValue);
+ public static <T> NavigableSet<T> asReversed(NavigableSet<T> self) {
+ return self.descendingSet();
}
- /**
- * @since 4.0.0
- */
- public static boolean isNotCase(Collection<?> caseValue, Object switchValue) {
- return !isCase(caseValue, switchValue);
- }
+ //--------------------------------------------------------------------------
+ // asString
/**
- * @since 4.0.0
+ * Get the detail information of {@link Throwable} instance's stack trace
+ *
+ * @param self a Throwable instance
+ * @return the detail information of stack trace
+ * @since 2.5.3
*/
- public static boolean isNotCase(Map<?, ?> caseValue, Object switchValue) {
- return !isCase(caseValue, switchValue);
+ public static String asString(Throwable self) {
+ StringBuilderWriter sw = new StringBuilderWriter();
+ try (PrintWriter pw = new PrintWriter(sw)) {
+ self.printStackTrace(pw);
+ }
+ return sw.toString();
}
//--------------------------------------------------------------------------
+ // asSynchronized
/**
- * Returns an iterator equivalent to this iterator with all duplicated items removed
- * by using Groovy's default number-aware comparator. The original iterator will become
- * exhausted of elements after determining the unique values. A new iterator
- * for the unique values will be returned.
+ * Creates a synchronized view of a Map.
*
- * @param self an Iterator
- * @return a new Iterator of the unique items from the original iterator
- * @since 1.5.5
+ * @param self a Map
+ * @return a synchronized Map
+ * @see java.util.Collections#synchronizedMap(java.util.Map)
+ * @since 1.0
*/
- public static <T> Iterator<T> unique(Iterator<T> self) {
- return uniqueItems(new IteratorIterableAdapter<>(self)).listIterator();
+ public static <K,V> Map<K,V> asSynchronized(Map<K,V> self) {
+ return Collections.synchronizedMap(self);
}
/**
- * Modifies this collection to remove all duplicated items, using Groovy's
- * default number-aware comparator.
- * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
+ * Creates a synchronized view of a SortedMap.
*
- * @param self a collection
- * @return the now modified collection
- * @see #unique(Collection, boolean)
+ * @param self a SortedMap
+ * @return a synchronized SortedMap
+ * @see java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
* @since 1.0
*/
- public static <T> Collection<T> unique(Collection<T> self) {
- return unique(self, true);
+ public static <K,V> SortedMap<K,V> asSynchronized(SortedMap<K,V> self) {
+ return Collections.synchronizedSortedMap(self);
}
/**
- * Modifies this List to remove all duplicated items, using Groovy's
- * default number-aware comparator.
- * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
+ * Creates a synchronized view of a NavigableMap.
*
- * @param self a List
- * @return the now modified List
- * @see #unique(Collection, boolean)
- * @since 2.4.0
+ * @param self a NavigableMap
+ * @return a synchronized NavigableMap
+ * @see java.util.Collections#synchronizedNavigableMap(java.util.NavigableMap)
+ * @since 5.0.0
*/
- public static <T> List<T> unique(List<T> self) {
- return (List<T>) unique((Collection<T>) self, true);
+ public static <K,V> NavigableMap<K,V> asSynchronized(NavigableMap<K,V> self) {
+ return Collections.synchronizedNavigableMap(self);
}
/**
- * Remove all duplicates from a given Collection using Groovy's default number-aware comparator.
- * If mutate is true, it works by modifying the original object (and also returning it).
- * If mutate is false, a new collection is returned leaving the original unchanged.
- * <pre class="groovyTestCase">
- * assert [1,3] == [1,3,3].unique()
- * </pre>
- * <pre class="groovyTestCase">
- * def orig = [1, 3, 2, 3]
- * def uniq = orig.unique(false)
- * assert orig == [1, 3, 2, 3]
- * assert uniq == [1, 3, 2]
- * </pre>
+ * Creates a synchronized view of a Collection.
*
- * @param self a collection
- * @param mutate false will cause a new list containing unique items from the collection to be created, true will mutate collections in place
- * @return the now modified collection
- * @since 1.8.1
+ * @param self a Collection
+ * @return a synchronized Collection
+ * @see java.util.Collections#synchronizedCollection(java.util.Collection)
+ * @since 1.0
*/
- public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
- List<T> answer = uniqueItems(self);
- if (mutate) {
- self.clear();
- self.addAll(answer);
- }
- return mutate ? self : answer ;
- }
-
- private static <T> List<T> uniqueItems(Iterable<T> self) {
- List<T> answer = new ArrayList<>();
- for (T t : self) {
- boolean duplicated = false;
- for (T t2 : answer) {
- if (coercedEquals(t, t2)) {
- duplicated = true;
- break;
- }
- }
- if (!duplicated)
- answer.add(t);
- }
- return answer;
+ public static <T> Collection<T> asSynchronized(Collection<T> self) {
+ return Collections.synchronizedCollection(self);
}
/**
- * Remove all duplicates from a given List using Groovy's default number-aware comparator.
- * If mutate is true, it works by modifying the original object (and also returning it).
- * If mutate is false, a new collection is returned leaving the original unchanged.
- * <pre class="groovyTestCase">
- * assert [1,3] == [1,3,3].unique()
- * </pre>
- * <pre class="groovyTestCase">
- * def orig = [1, 3, 2, 3]
- * def uniq = orig.unique(false)
- * assert orig == [1, 3, 2, 3]
- * assert uniq == [1, 3, 2]
- * </pre>
+ * Creates a synchronized view of a List.
*
* @param self a List
- * @param mutate false will cause a new List containing unique items from the List to be created, true will mutate List in place
- * @return the now modified List
- * @since 2.4.0
+ * @return a synchronized List
+ * @see java.util.Collections#synchronizedList(java.util.List)
+ * @since 1.0
*/
- public static <T> List<T> unique(List<T> self, boolean mutate) {
- return (List<T>) unique((Collection<T>) self, mutate);
+ public static <T> List<T> asSynchronized(List<T> self) {
+ return Collections.synchronizedList(self);
}
/**
- * Provides a method that compares two comparables using Groovy's
- * default number aware comparator.
+ * Creates a synchronized view of a Set.
*
- * @param self a Comparable
- * @param other another Comparable
- * @return a -ve number, 0 or a +ve number according to Groovy's compareTo contract
- * @since 1.6.0
+ * @param self a Set
+ * @return a synchronized Set
+ * @see java.util.Collections#synchronizedSet(java.util.Set)
+ * @since 1.0
*/
- public static int numberAwareCompareTo(Comparable self, Comparable other) {
- return COMPARABLE_NUMBER_AWARE_COMPARATOR.compare(self, other);
+ public static <T> Set<T> asSynchronized(Set<T> self) {
+ return Collections.synchronizedSet(self);
}
/**
- * Returns an iterator equivalent to this iterator but with all duplicated items
- * removed by using a Closure to determine duplicate (equal) items.
- * The original iterator will be fully processed after the call.
- * <p>
- * If the closure takes a single parameter, the argument passed will be each element,
- * and the closure should return a value used for comparison (either using
- * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
- * If the closure takes two parameters, two items from the Iterator
- * will be passed as arguments, and the closure should return an
- * int value (with 0 indicating the items are not unique).
+ * Creates a synchronized view of a SortedSet.
*
- * @param self an Iterator
- * @param condition a Closure used to determine unique items
- * @return the modified Iterator
- * @since 1.5.5
+ * @param self a SortedSet
+ * @return a synchronized SortedSet
+ * @see java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
+ * @since 1.0
*/
- public static <T> Iterator<T> unique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
- Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
- ? new OrderBy<>(condition, true)
- : new ClosureComparator<>(condition);
- return unique(self, comparator);
+ public static <T> SortedSet<T> asSynchronized(SortedSet<T> self) {
+ return Collections.synchronizedSortedSet(self);
}
/**
- * A convenience method for making a collection unique using a Closure
- * to determine duplicate (equal) items.
- * <p>
- * If the closure takes a single parameter, the
- * argument passed will be each element, and the closure
- * should return a value used for comparison (either using
- * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
- * If the closure takes two parameters, two items from the collection
- * will be passed as arguments, and the closure should return an
- * int value (with 0 indicating the items are not unique).
- * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
- * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b {@code ->} a {@code <=>} b }</pre>
+ * Creates a synchronized view of a NavigableSet.
*
- * @param self a Collection
- * @param closure a 1 or 2 arg Closure used to determine unique items
- * @return self without any duplicates
- * @see #unique(Collection, boolean, Closure)
- * @since 1.0
+ * @param self a NavigableSet
+ * @return a synchronized NavigableSet
+ * @see java.util.Collections#synchronizedNavigableSet(java.util.NavigableSet)
+ * @since 5.0.0
*/
- public static <T> Collection<T> unique(Collection<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
- return unique(self, true, closure);
+ public static <T> NavigableSet<T> asSynchronized(NavigableSet<T> self) {
+ return Collections.synchronizedNavigableSet(self);
}
+ //--------------------------------------------------------------------------
+ // asType
+
/**
- * A convenience method for making a List unique using a Closure
- * to determine duplicate (equal) items.
- * <p>
- * If the closure takes a single parameter, the
- * argument passed will be each element, and the closure
- * should return a value used for comparison (either using
- * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
- * If the closure takes two parameters, two items from the List
- * will be passed as arguments, and the closure should return an
- * int value (with 0 indicating the items are not unique).
- * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
- * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b {@code ->} a {@code <=>} b }</pre>
+ * Converts the given iterable to another type.
*
- * @param self a List
- * @param closure a 1 or 2 arg Closure used to determine unique items
- * @return self without any duplicates
- * @see #unique(Collection, boolean, Closure)
- * @since 2.4.0
+ * @param iterable an Iterable
+ * @param clazz the desired class
+ * @return the object resulting from this type conversion
+ * @see #asType(Collection, Class)
+ * @since 2.4.12
*/
- public static <T> List<T> unique(List<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
- return (List<T>) unique((Collection<T>) self, true, closure);
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(Iterable iterable, Class<T> clazz) {
+ if (Collection.class.isAssignableFrom(clazz)) {
+ return asType((Collection) toList(iterable), clazz);
+ }
+
+ return asType((Object) iterable, clazz);
}
/**
- * A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
- * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
- * <p>
- * If the closure takes a single parameter, each element from the Collection will be passed to the closure. The closure
- * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
- * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
- * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
- * <pre class="groovyTestCase">
- * def orig = [1, 3, 4, 5]
- * def uniq = orig.unique(false) { it % 2 }
- * assert orig == [1, 3, 4, 5]
- * assert uniq == [1, 4]
- * </pre>
- * <pre class="groovyTestCase">
- * def orig = [2, 3, 3, 4]
- * def uniq = orig.unique(false) { a, b {@code ->} a {@code <=>} b }
- * assert orig == [2, 3, 3, 4]
- * assert uniq == [2, 3, 4]
- * </pre>
+ * Converts the given collection to another type. A default concrete
+ * type is used for List, Set, or SortedSet. If the given type has
+ * a constructor taking a collection, that is used. Otherwise, the
+ * call is deferred to {@link #asType(Object,Class)}. If this
+ * collection is already of the given type, the same instance is
+ * returned.
*
- * @param self a Collection
- * @param mutate false will always cause a new list to be created, true will mutate lists in place
- * @param closure a 1 or 2 arg Closure used to determine unique items
- * @return self without any duplicates
- * @since 1.8.1
+ * @param col a collection
+ * @param clazz the desired class
+ * @return the object resulting from this type conversion
+ * @see #asType(java.lang.Object, java.lang.Class)
+ * @since 1.0
*/
- public static <T> Collection<T> unique(Collection<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
- // use a comparator of one item or two
- int params = closure.getMaximumNumberOfParameters();
- if (params == 1) {
- self = unique(self, mutate, new OrderBy<>(closure, true));
- } else {
- self = unique(self, mutate, new ClosureComparator<>(closure));
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(Collection col, Class<T> clazz) {
+ if (col.getClass() == clazz) {
+ return (T) col;
+ }
+ if (clazz == List.class) {
+ return (T) asList(col);
+ }
+ if (clazz == Set.class) {
+ if (col instanceof Set) return (T) col;
+ return (T) new LinkedHashSet(col);
+ }
+ if (clazz == SortedSet.class) {
+ if (col instanceof SortedSet) return (T) col;
+ return (T) new TreeSet(col);
+ }
+ if (clazz == Queue.class) {
+ if (col instanceof Queue) return (T) col;
+ return (T) new LinkedList(col);
+ }
+ if (clazz == Stack.class) {
+ if (col instanceof Stack) return (T) col;
+ final Stack stack = new Stack();
+ stack.addAll(col);
+ return (T) stack;
}
- return self;
- }
- /**
- * A convenience method for making a List unique using a Closure to determine duplicate (equal) items.
- * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
- * <p>
- * If the closure takes a single parameter, each element from the List will be passed to the closure. The closure
- * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
- * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
- * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
- * <pre class="groovyTestCase">
- * def orig = [1, 3, 4, 5]
- * def uniq = orig.unique(false) { it % 2 }
- * assert orig == [1, 3, 4, 5]
- * assert uniq == [1, 4]
- * </pre>
- * <pre class="groovyTestCase">
- * def orig = [2, 3, 3, 4]
- * def uniq = orig.unique(false) { a, b {@code ->} a {@code <=>} b }
- * assert orig == [2, 3, 3, 4]
- * assert uniq == [2, 3, 4]
- * </pre>
- *
- * @param self a List
- * @param mutate false will always cause a new list to be created, true will mutate lists in place
- * @param closure a 1 or 2 arg Closure used to determine unique items
- * @return self without any duplicates
- * @since 2.4.0
- */
- public static <T> List<T> unique(List<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
- return (List<T>) unique((Collection<T>) self, mutate, closure);
+ if (clazz!=String[].class && ReflectionCache.isArray(clazz)) {
+ try {
+ return (T) asArrayType(col, clazz);
+ } catch (GroovyCastException e) {
+ /* ignore */
+ }
+ }
+
+ Object[] args = {col};
+ try {
+ return (T) InvokerHelper.invokeConstructorOf(clazz, args);
+ } catch (Exception e) {
+ // ignore, the constructor that takes a Collection as an argument may not exist
+ }
+ if (Collection.class.isAssignableFrom(clazz)) {
+ try {
+ Collection result = (Collection) InvokerHelper.invokeConstructorOf(clazz, null);
+ result.addAll(col);
+ return (T)result;
+ } catch (Exception e) {
+ // ignore, the no arg constructor might not exist.
+ }
+ }
+
+ return asType((Object) col, clazz);
}
/**
- * Returns an iterator equivalent to this iterator with all duplicated
- * items removed by using the supplied comparator. The original iterator
- * will be exhausted upon returning.
+ * Coerces the closure to an implementation of the given class. The class
+ * is assumed to be an interface or class with a single method definition.
+ * The closure is used as the implementation of that single method.
*
- * @param self an Iterator
- * @param comparator a Comparator
- * @return the modified Iterator
- * @since 1.5.5
+ * @param impl the implementation of the single method
+ * @param type the target type
+ * @return A proxy of the given type which wraps this closure.
+ *
+ * @since 1.0
*/
- public static <T> Iterator<T> unique(Iterator<T> self, Comparator<? super T> comparator) {
- return uniqueItems(new IteratorIterableAdapter<>(self), comparator).listIterator();
- }
-
- private static final class IteratorIterableAdapter<T> implements Iterable<T> {
- private final Iterator<T> self;
-
- private IteratorIterableAdapter(Iterator<T> self) {
- this.self = self;
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(final Closure impl, final Class<T> type) {
+ if (type.isInterface() && !type.isInstance(impl)) {
+ return (T) CachedSAMClass.coerceToSAM(impl, CachedSAMClass.getSAMMethod(type), type, true);
}
- @Override
- public Iterator<T> iterator() {
- return self;
+ try {
+ return asType((Object) impl, type);
+ } catch (GroovyCastException gce) {
+ try {
+ return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(impl, type);
+ } catch (GroovyRuntimeException gre) {
+ throw new GroovyCastException("Error casting closure to " + type.getName() + ", Reason: " + gre.getMessage());
+ }
}
}
/**
- * Remove all duplicates from a given Collection.
- * Works on the original object (and also returns it).
- * The order of members in the Collection are compared by the given Comparator.
- * For each duplicate, the first member which is returned
- * by the given Collection's iterator is retained, but all other ones are removed.
- * The given Collection's original order is preserved.
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
- *
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
- *
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
- * }
- *
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
- *
- * def list = [a, b, c, d]
- * List list2 = list.unique(new PersonComparator())
- * assert( list2 == list {@code &&} list == [a, b, c] )
- * </pre>
+ * Coerces this map to the given type, using the map's keys as the public
+ * method names, and values as the implementation. Typically the value
+ * would be a closure which behaves like the method implementation.
*
- * @param self a Collection
- * @param comparator a Comparator
- * @return self the now modified collection without duplicates
- * @see #unique(java.util.Collection, boolean, java.util.Comparator)
+ * @param map this map
+ * @param clazz the target type
+ * @return a Proxy of the given type, which defers calls to this map's elements.
* @since 1.0
*/
- public static <T> Collection<T> unique(Collection<T> self, Comparator<? super T> comparator) {
- return unique(self, true, comparator) ;
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(Map map, Class<T> clazz) {
+ if (!(clazz.isInstance(map)) && clazz.isInterface() && !Traits.isTrait(clazz)) {
+ return (T) Proxy.newProxyInstance(
+ clazz.getClassLoader(),
+ new Class[]{clazz},
+ new ConvertedMap(map));
+ }
+ try {
+ return asType((Object) map, clazz);
+ } catch (GroovyCastException ce) {
+ try {
+ return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(map, clazz);
+ } catch (GroovyRuntimeException cause) {
+ throw new GroovyCastException("Error casting map to " + clazz.getName() +
+ ", Reason: " + cause.getMessage());
+ }
+ }
}
/**
- * Remove all duplicates from a given List.
- * Works on the original object (and also returns it).
- * The order of members in the List are compared by the given Comparator.
- * For each duplicate, the first member which is returned
- * by the given List's iterator is retained, but all other ones are removed.
- * The given List's original order is preserved.
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
+ * Transform this number to the given type, using the 'as' operator. The
+ * following types are supported in addition to the default
+ * {@link #asType(java.lang.Object, java.lang.Class)}:
+ * <ul>
+ * <li>BigDecimal</li>
+ * <li>BigInteger</li>
+ * <li>Double</li>
+ * <li>Float</li>
+ * </ul>
+ * @param self this number
+ * @param type the desired type of the transformed result
+ * @return an instance of the given type
+ * @since 1.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(Number self, Class<T> type) {
+ if (type == BigDecimal.class) {
+ return (T) toBigDecimal(self);
+ } else if (type == BigInteger.class) {
+ return (T) toBigInteger(self);
+ } else if (type == Double.class) {
+ return (T) toDouble(self);
+ } else if (type == Float.class) {
+ return (T) toFloat(self);
+ }
+ return asType((Object) self, type);
+ }
+
+ /**
+ * Converts a given object to a type. This method is used through
+ * the "as" operator and is overloadable as any other operator.
+ *
+ * @param obj the object to convert
+ * @param type the goal type
+ * @return the resulting object
+ * @since 1.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T asType(Object obj, Class<T> type) {
+ if (String.class == type) {
+ return (T) FormatHelper.toString(obj);
+ }
+
+ // fall back to cast
+ try {
+ return (T) DefaultTypeTransformation.castToType(obj, type);
+ }
+ catch (GroovyCastException e) {
+ MetaClass mc = InvokerHelper.getMetaClass(obj);
+ if (mc instanceof ExpandoMetaClass) {
+ ExpandoMetaClass emc = (ExpandoMetaClass) mc;
+ Object mixedIn = emc.castToMixedType(obj, type);
+ if (mixedIn != null)
+ return (T) mixedIn;
+ }
+ if (type.isInterface()) {
+ try {
+ List<Class> interfaces = new ArrayList<>();
+ interfaces.add(type);
+ return (T) ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, obj);
+ } catch (GroovyRuntimeException cause) {
+ // ignore
+ }
+ }
+ throw e;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Object asArrayType(Object object, Class type) {
+ if (type.isAssignableFrom(object.getClass())) {
+ return object;
+ }
+ Collection list = DefaultTypeTransformation.asCollection(object);
+ int size = list.size();
+ Class elementType = type.getComponentType();
+ Object array = Array.newInstance(elementType, size);
+ int idx = 0;
+
+ if (boolean.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setBoolean(array, idx, (Boolean) invokeAsType(element, boolean.class));
+ }
+ } else if (byte.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setByte(array, idx, (Byte) invokeAsType(element, byte.class));
+ }
+ } else if (char.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setChar(array, idx, (Character) invokeAsType(element, char.class));
+ }
+ } else if (double.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setDouble(array, idx, (Double) invokeAsType(element, double.class));
+ }
+ } else if (float.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setFloat(array, idx, (Float) invokeAsType(element, float.class));
+ }
+ } else if (int.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setInt(array, idx, (Integer) invokeAsType(element, int.class));
+ }
+ } else if (long.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setLong(array, idx, (Long) invokeAsType(element, long.class));
+ }
+ } else if (short.class.equals(elementType)) {
+ for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.setShort(array, idx, (Short) invokeAsType(element, short.class));
+ }
+ } else for (Iterator iter = list.iterator(); iter.hasNext(); idx++) {
+ Object element = iter.next();
+ Array.set(array, idx, invokeAsType(element, elementType));
+ }
+ return array;
+ }
+
+ private static Object invokeAsType(Object element, Class<?> elementType) {
+ Class<?> target = element instanceof CharSequence ? StringGroovyMethods.class : DefaultGroovyMethods.class;
+ return InvokerHelper.invokeStaticMethod(target, "asType", new Object[]{element, elementType});
+ }
+
+ //--------------------------------------------------------------------------
+ // asUnmodifiable
+
+ /**
+ * Creates an unmodifiable view of a Map.
+ *
+ * @param self a Map
+ * @return an unmodifiable view of the Map
+ * @see java.util.Collections#unmodifiableMap(java.util.Map)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 2.5.0
+ */
+ public static <K,V> Map<K,V> asUnmodifiable(Map<K,V> self) {
+ return Collections.unmodifiableMap(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a SortedMap.
+ *
+ * @param self a SortedMap
+ * @return an unmodifiable view of the SortedMap
+ * @see java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 2.5.0
+ */
+ public static <K,V> SortedMap<K,V> asUnmodifiable(SortedMap<K,V> self) {
+ return Collections.unmodifiableSortedMap(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a NavigableMap.
+ *
+ * @param self a NavigableMap
+ * @return an unmodifiable view of the NavigableMap
+ * @see java.util.Collections#unmodifiableNavigableMap(java.util.NavigableMap)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 5.0.0
+ */
+ public static <K,V> SortedMap<K,V> asUnmodifiable(NavigableMap<K,V> self) {
+ return Collections.unmodifiableNavigableMap(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a List.
+ * <pre class="groovyTestCase">
+ * def mutable = [1,2,3]
+ * def unmodifiable = mutable.asUnmodifiable()
+ * try {
+ * unmodifiable << 4
+ * assert false
+ * } catch (UnsupportedOperationException) {
+ * assert true
+ * }
+ * mutable << 4
+ * assert unmodifiable.size() == 4
+ * </pre>
+ *
+ * @param self a List
+ * @return an unmodifiable view of the List
+ * @see java.util.Collections#unmodifiableList(java.util.List)
+ * @since 2.5.0
+ */
+ public static <T> List<T> asUnmodifiable(List<T> self) {
+ return Collections.unmodifiableList(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a Set.
+ *
+ * @param self a Set
+ * @return an unmodifiable view of the Set
+ * @see java.util.Collections#unmodifiableSet(java.util.Set)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 2.5.0
+ */
+ public static <T> Set<T> asUnmodifiable(Set<T> self) {
+ return Collections.unmodifiableSet(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a SortedSet.
+ *
+ * @param self a SortedSet
+ * @return an unmodifiable view of the SortedSet
+ * @see java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 2.5.0
+ */
+ public static <T> SortedSet<T> asUnmodifiable(SortedSet<T> self) {
+ return Collections.unmodifiableSortedSet(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a NavigableSet.
+ *
+ * @param self a NavigableSet
+ * @return an unmodifiable view of the NavigableSet
+ * @see java.util.Collections#unmodifiableNavigableSet(java.util.NavigableSet)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 5.0.0
+ */
+ public static <T> NavigableSet<T> asUnmodifiable(NavigableSet<T> self) {
+ return Collections.unmodifiableNavigableSet(self);
+ }
+
+ /**
+ * Creates an unmodifiable view of a Collection.
+ *
+ * @param self a Collection
+ * @return an unmodifiable view of the Collection
+ * @see java.util.Collections#unmodifiableCollection(java.util.Collection)
+ * @see #asUnmodifiable(java.util.List)
+ * @since 2.5.0
+ */
+ public static <T> Collection<T> asUnmodifiable(Collection<T> self) {
+ return Collections.unmodifiableCollection(self);
+ }
+
+ //--------------------------------------------------------------------------
+ // average
+
+ /**
+ * Averages the items in an Iterable. This is equivalent to invoking the
+ * "plus" method on all items in the Iterable and then dividing by the
+ * total count using the "div" method for the resulting sum.
+ * <pre class="groovyTestCase">
+ * assert 3 == [1, 2, 6].average()
+ * </pre>
+ *
+ * @param self Iterable of values to average
+ * @return The average of all the items
+ * @see #average(Iterator)
+ * @since 3.0.0
+ */
+ public static Object average(Iterable<?> self) {
+ return average(self.iterator());
+ }
+
+ /**
+ * Averages the items from an Iterator. This is equivalent to invoking the
+ * "plus" method on all items in the array and then dividing by the
+ * total count using the "div" method for the resulting sum.
+ * The iterator will become exhausted of elements after determining the average value.
+ * While most frequently used with aggregates of numbers,
+ * {@code average} will work with any class supporting {@code plus} and {@code div}, e.g.:
+ * <pre class="groovyTestCase">
+ * class Stars {
+ * int numStars = 0
* String toString() {
- * return fname + " " + lname
+ * '*' * numStars
+ * }
+ * Stars plus(Stars other) {
+ * new Stars(numStars: numStars + other.numStars)
+ * }
+ * Stars div(Number divisor) {
+ * int newSize = numStars.intdiv(divisor)
+ * new Stars(numStars: newSize)
* }
* }
- *
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
- *
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
+ *
+ * def stars = [new Stars(numStars: 1), new Stars(numStars: 3)]
+ * assert stars*.toString() == ['*', '***']
+ * assert stars.average().toString() == '**'
+ * </pre>
+ *
+ * @param self an Iterator for the values to average
+ * @return The average of all the items
+ * @since 3.0.0
+ */
+ public static Object average(Iterator<?> self) {
+ Object result = null;
+ long count = 0;
+ Object[] param = new Object[1];
+ while (self.hasNext()) {
+ param[0] = self.next();
+ if (count == 0) {
+ result = param[0];
+ } else {
+ MetaClass metaClass = InvokerHelper.getMetaClass(result);
+ result = metaClass.invokeMethod(result, "plus", param);
+ }
+ count++;
+ }
+ MetaClass metaClass = InvokerHelper.getMetaClass(result);
+ result = metaClass.invokeMethod(result, "div", count);
+ return result;
+ }
+
+ /**
+ * Averages the result of applying a closure to each item of an Iterable.
+ * <code>iter.average(closure)</code> is equivalent to:
+ * <code>iter.collect(closure).average()</code>.
+ * <pre class="groovyTestCase">
+ * assert 20 == [1, 3].average { it * 10 }
+ * assert 3 == ['to', 'from'].average { it.size() }
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param closure a single parameter closure that returns a (typically) numeric value.
+ * @return The average of the values returned by applying the closure to each
+ * item of the Iterable.
+ * @since 3.0.0
+ */
+ public static <T> Object average(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return average(self.iterator(), closure);
+ }
+
+ /**
+ * Averages the result of applying a closure to each item returned from an iterator.
+ * <code>iter.average(closure)</code> is equivalent to:
+ * <code>iter.collect(closure).average()</code>.
+ * The iterator will become exhausted of elements after determining the average value.
+ *
+ * @param self An Iterator
+ * @param closure a single parameter closure that returns a (typically) numeric value.
+ * @return The average of the values returned by applying the closure to each
+ * item from the Iterator.
+ * @since 3.0.0
+ */
+ public static <T> Object average(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ Object result = null;
+ long count = 0;
+ Object[] closureParam = new Object[1];
+ Object[] plusParam = new Object[1];
+ while (self.hasNext()) {
+ closureParam[0] = self.next();
+ plusParam[0] = closure.call(closureParam);
+ if (count == 0) {
+ result = plusParam[0];
+ } else {
+ MetaClass metaClass = InvokerHelper.getMetaClass(result);
+ result = metaClass.invokeMethod(result, "plus", plusParam);
+ }
+ count++;
+ }
+ MetaClass metaClass = InvokerHelper.getMetaClass(result);
+ result = metaClass.invokeMethod(result, "div", count);
+ return result;
+ }
+
+ //--------------------------------------------------------------------------
+
+ /**
+ * Identity check. Since == is overridden in Groovy with the meaning of equality
+ * we need some fallback to check for object identity. Invoke using the
+ * 'is' method, like so: <code>def same = this.is(that)</code>
+ *
+ * @param self an object
+ * @param other an object to compare identity with
+ * @return true if self and other are both references to the same
+ * instance, false otherwise
+ * @since 1.0
+ */
+ public static boolean is(Object self, Object other) {
+ return self == other;
+ }
+
+ /**
+ * Allows the closure to be called for the object reference self.
+ * Synonym for 'with()'.
+ *
+ * @param self the object to have a closure act upon
+ * @param closure the closure to call on the object
+ * @return result of calling the closure
+ * @see #with(Object, Closure)
+ * @since 1.0
+ */
+ public static <T,U> T identity(
+ @DelegatesTo.Target("self") U self,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
+ return DefaultGroovyMethods.with(self, closure);
+ }
+
+ /**
+ * Allows the closure to be called for the object reference self.
+ * <p>
+ * Any method invoked inside the closure will first be invoked on the
+ * self reference. For instance, the following method calls to the append()
+ * method are invoked on the StringBuilder instance:
+ * <pre class="groovyTestCase">
+ * def b = new StringBuilder().with {
+ * append('foo')
+ * append('bar')
+ * return it
+ * }
+ * assert b.toString() == 'foobar'
+ * </pre>
+ * This is commonly used to simplify object creation, such as this example:
+ * <pre>
+ * def p = new Person().with {
+ * firstName = 'John'
+ * lastName = 'Doe'
+ * return it
* }
+ * </pre>
+ * The other typical usage, uses the self object while creating some value:
+ * <pre>
+ * def fullName = person.with{ "$firstName $lastName" }
+ * </pre>
*
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
+ * @param self the object to have a closure act upon
+ * @param closure the closure to call on the object
+ * @return result of calling the closure
+ * @see #with(Object, boolean, Closure)
+ * @see #tap(Object, Closure)
+ * @since 1.5.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T,U> T with(
+ @DelegatesTo.Target("self") U self,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
+ return (T) with(self, false, (Closure<Object>)closure);
+ }
+
+ /**
+ * Allows the closure to be called for the object reference self.
+ * <p/>
+ * Any method invoked inside the closure will first be invoked on the
+ * self reference. For example, the following method calls to the append()
+ * method are invoked on the StringBuilder instance and then, because
+ * 'returning' is true, the self instance is returned:
+ * <pre class="groovyTestCase">
+ * def b = new StringBuilder().with(true) {
+ * append('foo')
+ * append('bar')
+ * }
+ * assert b.toString() == 'foobar'
+ * </pre>
+ * The returning parameter is commonly set to true when using with to simplify object
+ * creation, such as this example:
+ * <pre>
+ * def p = new Person().with(true) {
+ * firstName = 'John'
+ * lastName = 'Doe'
+ * }
+ * </pre>
+ * Alternatively, 'tap' is an alias for 'with(true)', so that method can be used instead.
*
- * def list = [a, b, c, d]
- * List list2 = list.unique(new PersonComparator())
- * assert( list2 == list {@code &&} list == [a, b, c] )
+ * The other main use case for with is when returning a value calculated using self as shown here:
+ * <pre>
+ * def fullName = person.with(false){ "$firstName $lastName" }
* </pre>
+ * Alternatively, 'with' is an alias for 'with(false)', so the boolean parameter can be omitted instead.
*
- * @param self a List
- * @param comparator a Comparator
- * @return self the now modified List without duplicates
- * @see #unique(java.util.Collection, boolean, java.util.Comparator)
- * @since 2.4.0
+ * @param self the object to have a closure act upon
+ * @param returning if true, return the self object; otherwise, the result of calling the closure
+ * @param closure the closure to call on the object
+ * @return the self object or the result of calling the closure depending on 'returning'
+ * @see #with(Object, Closure)
+ * @see #tap(Object, Closure)
+ * @since 2.5.0
*/
- public static <T> List<T> unique(List<T> self, Comparator<? super T> comparator) {
- return (List<T>) unique((Collection<T>) self, true, comparator);
+ public static <T,U extends T, V extends T> T with(
+ @DelegatesTo.Target("self") U self,
+ boolean returning,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
+ @SuppressWarnings("unchecked")
+ final Closure<V> clonedClosure = (Closure<V>) closure.clone();
+ clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
+ clonedClosure.setDelegate(self);
+ V result = clonedClosure.call(self);
+ return returning ? self : result;
}
/**
- * Remove all duplicates from a given Collection.
- * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new collection is returned.
- * The order of members in the Collection are compared by the given Comparator.
- * For each duplicate, the first member which is returned
- * by the given Collection's iterator is retained, but all other ones are removed.
- * The given Collection's original order is preserved.
+ * Allows the closure to be called for the object reference self (similar
+ * to <code>with</code>) and always returns self.
* <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
+ * Any method invoked inside the closure will first be invoked on the
+ * self reference. For instance, the following method calls to the append()
+ * method are invoked on the StringBuilder instance:
+ * <pre>
+ * def b = new StringBuilder().tap {
+ * append('foo')
+ * append('bar')
+ * }
+ * assert b.toString() == 'foobar'
+ * </pre>
+ * This is commonly used to simplify object creation, such as this example:
+ * <pre>
+ * def p = new Person().tap {
+ * firstName = 'John'
+ * lastName = 'Doe'
* }
+ * </pre>
*
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
+ * @param self the object to have a closure act upon
+ * @param closure the closure to call on the object
+ * @return self
+ * @see #with(Object, boolean, Closure)
+ * @see #with(Object, Closure)
+ * @since 2.5.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T,U> U tap(
+ @DelegatesTo.Target("self") U self,
+ @DelegatesTo(value=DelegatesTo.Target.class,
+ target="self",
+ strategy=Closure.DELEGATE_FIRST)
+ @ClosureParams(FirstParam.class)
+ Closure<T> closure) {
+ return (U) with(self, true, (Closure<Object>)closure);
+ }
+
+ /**
+ * Allows the subscript operator to be used to lookup dynamic property values.
+ * <code>bean[somePropertyNameExpression]</code>. The normal property notation
+ * of groovy is neater and more concise but only works with compile-time known
+ * property names.
*
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
- * }
+ * @param self the object to act upon
+ * @param property the property name of interest
+ * @return the property value
+ * @since 1.0
+ */
+ public static Object getAt(Object self, String property) {
+ return InvokerHelper.getProperty(self, property);
+ }
+
+ /**
+ * Allows the subscript operator to be used to set dynamically named property values.
+ * <code>bean[somePropertyNameExpression] = foo</code>. The normal property notation
+ * of groovy is neater and more concise but only works with property names which
+ * are known at compile time.
*
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
+ * @param self the object to act upon
+ * @param property the name of the property to set
+ * @param newValue the value to set
+ * @since 1.0
+ */
+ public static void putAt(Object self, String property, Object newValue) {
+ InvokerHelper.setProperty(self, property, newValue);
+ }
+
+ /**
+ * Generates a detailed dump string of an object showing its class,
+ * hashCode and all accessible fields.
*
- * def list = [a, b, c, d]
- * List list2 = list.unique(false, new PersonComparator())
- * assert( list2 != list {@code &&} list2 == [a, b, c] )
- * </pre>
+ * @param self an object
+ * @return the dump representation
+ * @since 1.0
+ */
+ public static String dump(Object self) {
+ if (self == null) {
+ return "null";
+ }
+ StringBuilder buffer = new StringBuilder("<");
+ Class<?> klass = self.getClass();
+ buffer.append(klass.getName());
+ buffer.append("@");
+ buffer.append(Integer.toHexString(self.hashCode()));
+ boolean groovyObject = self instanceof GroovyObject;
+ while (klass != null) {
+ for (Field field : klass.getDeclaredFields()) {
+ if (Modifier.isStatic(field.getModifiers()) || (groovyObject && field.getName().equals("metaClass"))) {
+ continue;
+ }
+ buffer.append(" ");
+ buffer.append(field.getName());
+ buffer.append("=");
+ if (!field.canAccess(self)) { // GROOVY-9144
+ if (!SystemUtil.getBooleanSafe("groovy.force.illegal.access")
+ || ReflectionUtils.makeAccessibleInPrivilegedAction(field).isEmpty()) {
+ buffer.append("inaccessible");
+ continue;
+ }
+ }
+ try {
+ buffer.append(FormatHelper.toString(field.get(self)));
+ } catch (Exception e) {
+ buffer.append(e);
+ }
+ }
+ klass = klass.getSuperclass();
+ }
+ buffer.append(">");
+ return buffer.toString();
+ }
+
+ /**
+ * Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it
+ * in a list of {@link groovy.lang.PropertyValue} objects that additionally provide
+ * the value for each property of 'self'.
*
- * @param self a Collection
- * @param mutate false will always cause a new collection to be created, true will mutate collections in place
- * @param comparator a Comparator
- * @return self the collection without duplicates
- * @since 1.8.1
+ * @param self the receiver object
+ * @return list of {@link groovy.lang.PropertyValue} objects
+ * @see groovy.util.Expando#getMetaPropertyValues()
+ * @since 1.0
*/
- public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<? super T> comparator) {
- List<T> answer = uniqueItems(self, comparator);
- if (mutate) {
- self.clear();
- self.addAll(answer);
+ public static List<PropertyValue> getMetaPropertyValues(Object self) {
+ MetaClass metaClass = InvokerHelper.getMetaClass(self);
+ List<MetaProperty> mps = metaClass.getProperties();
+ List<PropertyValue> props = new ArrayList<>(mps.size());
+ for (MetaProperty mp : mps) {
+ props.add(new PropertyValue(self, mp));
}
- return mutate ? self : answer;
+ return props;
}
- private static <T> List<T> uniqueItems(Iterable<T> self, Comparator<? super T> comparator) {
- List<T> answer = new ArrayList<>();
- for (T t : self) {
- boolean duplicated = false;
- for (T t2 : answer) {
- if (comparator.compare(t, t2) == 0) {
- duplicated = true;
- break;
- }
+ /**
+ * Convenience method that calls {@link #getMetaPropertyValues(java.lang.Object)}(self)
+ * and provides the data in form of simple key/value pairs, i.e. without
+ * type() information.
+ *
+ * @param self the receiver object
+ * @return meta properties as Map of key/value pairs
+ * @since 1.0
+ */
+ public static Map<String, Object> getProperties(Object self) {
+ List<PropertyValue> metaProps = getMetaPropertyValues(self);
+ Map<String, Object> props = new LinkedHashMap<>(metaProps.size());
+
+ for (PropertyValue mp : metaProps) {
+ try {
+ props.put(mp.getName(), mp.getValue());
+ } catch (Exception e) {
+ java.util.logging.Logger.getLogger(DefaultGroovyMethods.class.getName())
+ .throwing(self.getClass().getName(), "getProperty(" + mp.getName() + ")", e);
}
- if (!duplicated)
- answer.add(t);
}
- return answer;
+ return props;
}
/**
- * Remove all duplicates from a given List.
- * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new List is returned.
- * The order of members in the List are compared by the given Comparator.
- * For each duplicate, the first member which is returned
- * by the given List's iterator is retained, but all other ones are removed.
- * The given List's original order is preserved.
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
+ * Scoped use method
*
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
+ * @param self any Object
+ * @param categoryClass a category class to use
+ * @param closure the closure to invoke with the category in place
+ * @return the value returned from the closure
+ * @since 1.0
+ */
+ public static <T> T use(Object self, Class categoryClass, Closure<T> closure) {
+ return GroovyCategorySupport.use(categoryClass, closure);
+ }
+
+ /**
+ * Extend object with category methods.
+ * All methods for given class and all super classes will be added to the object.
*
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
- * }
+ * @param self any Class
+ * @param categoryClasses a category classes to use
+ * @since 1.6.0
+ */
+ public static void mixin(MetaClass self, List<Class> categoryClasses) {
+ MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
+ }
+
+ /**
+ * Extend class globally with category methods.
+ * All methods for given class and all super classes will be added to the class.
*
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
+ * @param self any Class
+ * @param categoryClasses a category classes to use
+ * @since 1.6.0
+ */
+ public static void mixin(Class self, List<Class> categoryClasses) {
+ mixin(getMetaClass(self), categoryClasses);
+ }
+
+ /**
+ * Extend class globally with category methods.
*
- * def list = [a, b, c, d]
- * List list2 = list.unique(false, new PersonComparator())
- * assert( list2 != list {@code &&} list2 == [a, b, c] )
- * </pre>
+ * @param self any Class
+ * @param categoryClass a category class to use
+ * @since 1.6.0
+ */
+ public static void mixin(Class self, Class categoryClass) {
+ mixin(getMetaClass(self), Collections.singletonList(categoryClass));
+ }
+
+ /**
+ * Extend class globally with category methods.
*
- * @param self a List
- * @param mutate false will always cause a new List to be created, true will mutate List in place
- * @param comparator a Comparator
- * @return self the List without duplicates
- * @since 2.4.0
+ * @param self any Class
+ * @param categoryClass a category class to use
+ * @since 1.6.0
*/
- public static <T> List<T> unique(List<T> self, boolean mutate, Comparator<? super T> comparator) {
- return (List<T>) unique((Collection<T>) self, mutate, comparator);
+ public static void mixin(Class self, Class[] categoryClass) {
+ mixin(getMetaClass(self), Arrays.asList(categoryClass));
}
/**
- * Returns an iterator equivalent to this iterator but with all duplicated items
- * removed where duplicate (equal) items are deduced by calling the supplied Closure condition.
- * <p>
- * If the supplied Closure takes a single parameter, the argument passed will be each element,
- * and the closure should return a value used for comparison (either using
- * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
- * If the closure takes two parameters, two items from the Iterator
- * will be passed as arguments, and the closure should return an
- * int value (with 0 indicating the items are not unique).
- * <pre class="groovyTestCase">
- * def items = "Hello".toList() + [null, null] + "there".toList()
- * def toLower = { it == null ? null : it.toLowerCase() }
- * def noDups = items.iterator().toUnique(toLower).toList()
- * assert noDups == ['H', 'e', 'l', 'o', null, 't', 'r']
- * </pre>
- * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].toUnique { it % 2 }</pre>
- * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].toUnique { a, b {@code ->} a {@code <=>} b }</pre>
+ * Extend class globally with category methods.
*
- * @param self an Iterator
- * @param condition a Closure used to determine unique items
- * @return an Iterator with no duplicate items
- * @since 2.4.0
+ * @param self any Class
+ * @param categoryClass a category class to use
+ * @since 1.6.0
*/
- public static <T> Iterator<T> toUnique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
- return toUnique(self, condition.getMaximumNumberOfParameters() == 1
- ? new OrderBy<>(condition, true)
- : new ClosureComparator<>(condition));
+ public static void mixin(MetaClass self, Class categoryClass) {
+ mixin(self, Collections.singletonList(categoryClass));
}
- private static final class ToUniqueIterator<E> implements Iterator<E> {
- private final Iterator<E> delegate;
- private final Set<E> seen;
- private boolean exhausted;
- private E next;
+ /**
+ * Extend class globally with category methods.
+ *
+ * @param self any Class
+ * @param categoryClass a category class to use
+ * @since 1.6.0
+ */
+ public static void mixin(MetaClass self, Class[] categoryClass) {
+ mixin(self, Arrays.asList(categoryClass));
+ }
- private ToUniqueIterator(Iterator<E> delegate, Comparator<? super E> comparator) {
- this.seen = new TreeSet<>(comparator);
- this.delegate = delegate;
- advance();
+ /**
+ * Gets the url of the jar file/source file containing the specified class
+ *
+ * @param self the class
+ * @return the url of the jar, {@code null} if the specified class is from JDK
+ * @since 2.5.0
+ */
+ public static URL getLocation(Class self) {
+ CodeSource codeSource = self.getProtectionDomain().getCodeSource();
+
+ return null == codeSource ? null : codeSource.getLocation();
+ }
+
+ /**
+ * Scoped use method with list of categories.
+ *
+ * @param self any Object
+ * @param categoryClassList a list of category classes
+ * @param closure the closure to invoke with the categories in place
+ * @return the value returned from the closure
+ * @since 1.0
+ */
+ public static <T> T use(Object self, List<Class> categoryClassList, Closure<T> closure) {
+ return GroovyCategorySupport.use(categoryClassList, closure);
+ }
+
+ /**
+ * Allows you to use a list of categories, specifying the list as varargs.
+ * <code>use(CategoryClass1, CategoryClass2) { ... }</code>
+ * This method saves having to wrap the category
+ * classes in a list.
+ *
+ * @param self any Object
+ * @param array a list of category classes and a Closure
+ * @return the value returned from the closure
+ * @since 1.0
+ */
+ @SuppressWarnings("unchecked")
+ public static Object use(Object self, Object[] array) {
+ if (array.length < 2)
+ throw new IllegalArgumentException(
+ "Expecting at least 2 arguments, a category class and a Closure");
+ Closure closure;
+ try {
+ closure = (Closure) array[array.length - 1];
+ } catch (ClassCastException e) {
+ throw new IllegalArgumentException("Expecting a Closure to be the last argument");
+ }
+ List<Class> list = new ArrayList<>(array.length - 1);
+ for (int i = 0; i < array.length - 1; ++i) {
+ Class categoryClass;
+ try {
+ categoryClass = (Class) array[i];
+ } catch (ClassCastException e) {
+ throw new IllegalArgumentException("Expecting a Category Class for argument " + i);
+ }
+ list.add(categoryClass);
}
+ return GroovyCategorySupport.use(list, closure);
+ }
- @Override
- public boolean hasNext() {
- return !exhausted;
+ private static Object getClosureOwner(Closure<?> cls) {
+ Object owner = cls.getOwner();
+ while (owner instanceof GeneratedClosure) {
+ owner = ((Closure<?>) owner).getOwner();
}
+ return owner;
+ }
- @Override
- public E next() {
- if (exhausted) throw new NoSuchElementException();
- E result = next;
- advance();
- return result;
- }
+ /**
+ * Inspects returns the String that matches what would be typed into a
+ * terminal to create this object.
+ *
+ * @param self any Object
+ * @return a String that matches what would be typed into a terminal to
+ * create this object. e.g. [1, 'hello'].inspect() {@code ->} [1, 'hello']
+ * @since 1.0
+ */
+ public static String inspect(Object self) {
+ return FormatHelper.inspect(self);
+ }
- @Override
- public void remove() {
- if (exhausted) throw new NoSuchElementException();
- delegate.remove();
- }
+ /**
+ * Provide a dynamic method invocation method which can be overloaded in
+ * classes to implement dynamic proxies easily.
+ *
+ * @param object any Object
+ * @param method the name of the method to call
+ * @param arguments the arguments to use
+ * @return the result of the method call
+ * @since 1.0
+ */
+ public static Object invokeMethod(Object object, String method, Object arguments) {
+ return InvokerHelper.invokeMethod(object, method, arguments);
+ }
- private void advance() {
- boolean foundNext = false;
- while (!foundNext && !exhausted) {
- exhausted = !delegate.hasNext();
- if (!exhausted) {
- next = delegate.next();
- foundNext = seen.add(next);
- }
+ //--------------------------------------------------------------------------
+ // print/println/printf/sprintf
+
+ /**
+ * Print a value formatted Groovy style to self if it
+ * is a Writer, otherwise to the standard output stream.
+ *
+ * @param self any Object
+ * @param value the value to print
+ * @since 1.0
+ */
+ public static void print(Object self, Object value) {
+ // we won't get here if we are a PrintWriter
+ if (self instanceof Writer) {
+ try {
+ ((Writer) self).write(FormatHelper.toString(value));
+ } catch (IOException e) {
+ // TODO: Should we have some unified function like PrintWriter.checkError()?
}
+ } else {
+ System.out.print(FormatHelper.toString(value));
}
}
/**
- * Returns an iterator equivalent to this iterator with all duplicated
- * items removed by using the supplied comparator.
+ * Print a value formatted Groovy style to the print writer.
*
- * @param self an Iterator
- * @param comparator a Comparator used to determine unique (equal) items
- * If {@code null}, the Comparable natural ordering of the elements will be used.
- * @return an Iterator with no duplicate items
- * @since 2.4.0
+ * @param self a PrintWriter
+ * @param value the value to print
+ * @since 1.0
*/
- public static <T> Iterator<T> toUnique(Iterator<T> self, Comparator<? super T> comparator) {
- return new ToUniqueIterator<>(self, comparator);
+ public static void print(PrintWriter self, Object value) {
+ self.print(FormatHelper.toString(value));
}
/**
- * Returns an iterator equivalent to this iterator with all duplicated
- * items removed by using the natural ordering of the items.
+ * Print a value formatted Groovy style to the print stream.
*
- * @param self an Iterator
- * @return an Iterator with no duplicate items
- * @since 2.4.0
+ * @param self a PrintStream
+ * @param value the value to print
+ * @since 1.6.0
*/
- public static <T> Iterator<T> toUnique(Iterator<T> self) {
- return toUnique(self, (Comparator<T>) null);
+ public static void print(PrintStream self, Object value) {
+ self.print(FormatHelper.toString(value));
}
/**
- * Returns a Collection containing the items from the Iterable but with duplicates removed.
- * The items in the Iterable are compared by the given Comparator.
- * For each duplicate, the first member which is returned from the
- * Iterable is retained, but all other ones are removed.
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
- *
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
- *
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
- * }
- *
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
- *
- * def list = [a, b, c, d]
- * List list2 = list.toUnique(new PersonComparator())
- * assert list2 == [a, b, c] {@code &&} list == [a, b, c, d]
- * </pre>
+ * Print a value to the standard output stream.
+ * This method delegates to the owner to execute the method.
*
- * @param self an Iterable
- * @param comparator a Comparator used to determine unique (equal) items
- * If {@code null}, the Comparable natural ordering of the elements will be used.
- * @return the Collection of non-duplicate items
- * @since 2.4.0
+ * @param self a generated closure
+ * @param value the value to print
+ * @since 1.0
*/
- public static <T> Collection<T> toUnique(Iterable<T> self, Comparator<? super T> comparator) {
- Collection<T> result = createSimilarCollection(self);
- addAll(result, toUnique(self.iterator(), comparator));
- return result;
+ public static void print(Closure self, Object value) {
+ Object owner = getClosureOwner(self);
+ InvokerHelper.invokeMethod(owner, "print", new Object[]{value});
}
/**
- * Returns a List containing the items from the List but with duplicates removed.
- * The items in the List are compared by the given Comparator.
- * For each duplicate, the first member which is returned from the
- * List is retained, but all other ones are removed.
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
- *
- * class PersonComparator implements Comparator {
- * int compare(Object o1, Object o2) {
- * Person p1 = (Person) o1
- * Person p2 = (Person) o2
- * if (p1.lname != p2.lname)
- * return p1.lname.compareTo(p2.lname)
- * else
- * return p1.fname.compareTo(p2.fname)
- * }
- *
- * boolean equals(Object obj) {
- * return this.equals(obj)
- * }
- * }
+ * Print to a console in interactive format.
*
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
+ * @param self any Object
+ * @param out the PrintWriter used for printing
+ * @since 1.0
+ */
+ public static void print(Object self, PrintWriter out) {
+ if (out == null) {
+ out = new PrintWriter(System.out);
+ }
+ out.print(FormatHelper.toString(self));
+ }
+
+ /**
+ * Print a linebreak to the standard output stream.
*
- * def list = [a, b, c, d]
- * List list2 = list.toUnique(new PersonComparator())
- * assert list2 == [a, b, c] {@code &&} list == [a, b, c, d]
- * </pre>
+ * @param self any Object
+ * @since 1.0
+ */
+ public static void println(Object self) {
+ // we won't get here if we are a PrintWriter
+ if (self instanceof Writer) {
+ PrintWriter pw = new GroovyPrintWriter((Writer) self);
+ pw.println();
+ } else {
+ System.out.println();
+ }
+ }
+
+ /**
+ * Print a linebreak to the standard output stream.
+ * This method delegates to the owner to execute the method.
*
- * @param self a List
- * @param comparator a Comparator used to determine unique (equal) items
- * If {@code null}, the Comparable natural ordering of the elements will be used.
- * @return the List of non-duplicate items
- * @since 2.4.0
+ * @param self a closure
+ * @since 1.0
*/
- public static <T> List<T> toUnique(List<T> self, Comparator<? super T> comparator) {
- return (List<T>) toUnique((Iterable<T>) self, comparator);
+ public static void println(Closure self) {
+ Object owner = getClosureOwner(self);
+ InvokerHelper.invokeMethod(owner, "println", InvokerHelper.EMPTY_ARGS);
}
/**
- * Returns a Collection containing the items from the Iterable but with duplicates removed
- * using the natural ordering of the items to determine uniqueness.
- * <p>
- * <pre class="groovyTestCase">
- * String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
- * String[] expected = ['c', 'a', 't', 's', 'h']
- * assert letters.toUnique() == expected
- * </pre>
+ * Print a value formatted Groovy style (followed by a newline) to self
+ * if it is a Writer, otherwise to the standard output stream.
+ *
+ * @param self any Object
+ * @param value the value to print
+ * @since 1.0
+ */
+ public static void println(Object self, Object value) {
+ // we won't get here if we are a PrintWriter
+ if (self instanceof Writer) {
+ final PrintWriter pw = new GroovyPrintWriter((Writer) self);
+ pw.println(value);
+ } else {
+ System.out.println(FormatHelper.toString(value));
+ }
+ }
+
+ /**
+ * Print a value formatted Groovy style (followed by a newline) to the print writer.
*
- * @param self an Iterable
- * @return the Collection of non-duplicate items
- * @since 2.4.0
+ * @param self a PrintWriter
+ * @param value the value to print
+ * @since 1.0
*/
- public static <T> Collection<T> toUnique(Iterable<T> self) {
- return toUnique(self, (Comparator<T>) null);
+ public static void println(PrintWriter self, Object value) {
+ self.println(FormatHelper.toString(value));
}
/**
- * Returns a List containing the items from the List but with duplicates removed
- * using the natural ordering of the items to determine uniqueness.
- * <p>
- * <pre class="groovyTestCase">
- * def letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
- * def expected = ['c', 'a', 't', 's', 'h']
- * assert letters.toUnique() == expected
- * </pre>
+ * Print a value formatted Groovy style (followed by a newline) to the print stream.
*
- * @param self a List
- * @return the List of non-duplicate items
- * @since 2.4.0
+ * @param self any Object
+ * @param value the value to print
+ * @since 1.6.0
*/
- public static <T> List<T> toUnique(List<T> self) {
- return toUnique(self, (Comparator<T>) null);
+ public static void println(PrintStream self, Object value) {
+ self.println(FormatHelper.toString(value));
}
/**
- * Returns a Collection containing the items from the Iterable but with duplicates removed.
- * The items in the Iterable are compared by the given Closure condition.
- * For each duplicate, the first member which is returned from the
- * Iterable is retained, but all other ones are removed.
- * <p>
- * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
- * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
- * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
- * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
- *
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
- *
- * def list = [a, b, c, d]
- * def list2 = list.toUnique{ p1, p2 {@code ->} p1.lname != p2.lname ? p1.lname <=> p2.lname : p1.fname <=> p2.fname }
- * assert( list2 == [a, b, c] {@code &&} list == [a, b, c, d] )
- * def list3 = list.toUnique{ it.toString() }
- * assert( list3 == [a, b, c] {@code &&} list == [a, b, c, d] )
- * </pre>
+ * Print a value (followed by a newline) to the standard output stream.
+ * This method delegates to the owner to execute the method.
*
- * @param self an Iterable
- * @param condition a Closure used to determine unique items
- * @return a new Collection
- * @see #toUnique(Iterable, Comparator)
- * @since 2.4.0
+ * @param self a closure
+ * @param value the value to print
+ * @since 1.0
*/
- public static <T> Collection<T> toUnique(Iterable<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
- Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
- ? new OrderBy<>(condition, true)
- : new ClosureComparator<>(condition);
- return toUnique(self, comparator);
+ public static void println(Closure self, Object value) {
+ Object owner = getClosureOwner(self);
+ InvokerHelper.invokeMethod(owner, "println", new Object[]{value});
}
/**
- * Returns a List containing the items from the List but with duplicates removed.
- * The items in the List are compared by the given Closure condition.
- * For each duplicate, the first member which is returned from the
- * Iterable is retained, but all other ones are removed.
- * <p>
- * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
- * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
- * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
- * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
- * <p>
- * <pre class="groovyTestCase">
- * class Person {
- * def fname, lname
- * String toString() {
- * return fname + " " + lname
- * }
- * }
- *
- * Person a = new Person(fname:"John", lname:"Taylor")
- * Person b = new Person(fname:"Clark", lname:"Taylor")
- * Person c = new Person(fname:"Tom", lname:"Cruz")
- * Person d = new Person(fname:"Clark", lname:"Taylor")
- *
- * def list = [a, b, c, d]
- * def list2 = list.toUnique{ p1, p2 {@code ->} p1.lname != p2.lname ? p1.lname <=> p2.lname : p1.fname <=> p2.fname }
- * assert( list2 == [a, b, c] {@code &&} list == [a, b, c, d] )
- * def list3 = list.toUnique{ it.toString() }
- * assert( list3 == [a, b, c] {@code &&} list == [a, b, c, d] )
- * </pre>
+ * Print to a console in interactive format.
*
- * @param self a List
- * @param condition a Closure used to determine unique items
- * @return a new List
- * @see #toUnique(Iterable, Comparator)
- * @since 2.4.0
+ * @param self any Object
+ * @param out the PrintWriter used for printing
+ * @since 1.0
*/
- public static <T> List<T> toUnique(List<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
- return (List<T>) toUnique((Iterable<T>) self, condition);
+ public static void println(Object self, PrintWriter out) {
+ if (out == null) {
+ out = new PrintWriter(System.out);
+ }
+ out.println(FormatHelper.toString(self));
}
/**
- * Iterates through an aggregate type or data structure,
- * passing each item to the given closure. Custom types may utilize this
- * method by simply providing an "iterator()" method. The items returned
- * from the resulting iterator will be passed to the closure.
- * <pre class="groovyTestCase">
- * String result = ''
- * ['a', 'b', 'c'].each{ result += it }
- * assert result == 'abc'
- * </pre>
+ * Printf to the standard output stream.
*
- * @param self the object over which we iterate
- * @param closure the closure applied on each element found
- * @return the self Object
+ * @param self any Object
+ * @param format a format string
+ * @param values values referenced by the format specifiers in the format string
* @since 1.0
*/
- public static <T> T each(T self, @ClosureParams(value=FromString.class, options="?") Closure closure) {
- each(InvokerHelper.asIterator(self), closure);
- return self;
+ public static void printf(Object self, String format, Object[] values) {
+ if (self instanceof PrintStream)
+ ((PrintStream)self).printf(format, values);
+ else
+ System.out.printf(format, values);
}
/**
- * Iterates through an aggregate type or data structure,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
- * <pre class="groovyTestCase">
- * String result = ''
- * ['a', 'b', 'c'].eachWithIndex{ letter, index {@code ->} result += "$index:$letter" }
- * assert result == '0:a1:b2:c'
- * </pre>
+ * Printf 0 or more values to the standard output stream using a format string.
+ * This method delegates to the owner to execute the method.
*
- * @param self an Object
- * @param closure a Closure to operate on each item
- * @return the self Object
- * @since 1.0
+ * @param self a generated closure
+ * @param format a format string
+ * @param values values referenced by the format specifiers in the format string
+ * @since 3.0.0
*/
- public static <T> T eachWithIndex(T self, @ClosureParams(value=FromString.class, options="?,Integer") Closure closure) {
- final Object[] args = new Object[2];
- int counter = 0;
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
- args[0] = iter.next();
- args[1] = counter++;
- closure.call(args);
- }
- return self;
+ public static void printf(Closure self, String format, Object[] values) {
+ Object owner = getClosureOwner(self);
+ Object[] newValues = new Object[values.length + 1];
+ newValues[0] = format;
+ System.arraycopy(values, 0, newValues, 1, values.length);
+ InvokerHelper.invokeMethod(owner, "printf", newValues);
}
/**
- * Iterates through an iterable type,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Printf a value to the standard output stream using a format string.
+ * This method delegates to the owner to execute the method.
*
- * @param self an Iterable
- * @param closure a Closure to operate on each item
- * @return the self Iterable
- * @since 2.3.0
+ * @param self a generated closure
+ * @param format a format string
+ * @param value value referenced by the format specifier in the format string
+ * @since 3.0.0
*/
- public static <T> Iterable<T> eachWithIndex(Iterable<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- eachWithIndex(self.iterator(), closure);
- return self;
+ public static void printf(Closure self, String format, Object value) {
+ Object owner = getClosureOwner(self);
+ Object[] newValues = new Object[2];
+ newValues[0] = format;
+ newValues[1] = value;
+ InvokerHelper.invokeMethod(owner, "printf", newValues);
}
/**
- * Iterates through an iterator type,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Prints a formatted string using the specified format string and arguments.
+ * <p>
+ * Examples:
+ * <pre>
+ * printf ( "Hello, %s!\n" , [ "world" ] as String[] )
+ * printf ( "Hello, %s!\n" , [ "Groovy" ])
+ * printf ( "%d + %d = %d\n" , [ 1 , 2 , 1+2 ] as Integer[] )
+ * printf ( "%d + %d = %d\n" , [ 3 , 3 , 3+3 ])
*
- * @param self an Iterator
- * @param closure a Closure to operate on each item
- * @return the self Iterator (now exhausted)
- * @since 2.3.0
+ * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as Integer[] ) }
+ * ( 1..5 ).each { printf ( "-- %d\n" , [ it ] as int[] ) }
+ * ( 0x41..0x45 ).each { printf ( "-- %c\n" , [ it ] as char[] ) }
+ * ( 07..011 ).each { printf ( "-- %d\n" , [ it ] as byte[] ) }
+ * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as short[] ) }
+ * ( 7..11 ).each { printf ( "-- %d\n" , [ it ] as long[] ) }
+ * ( 7..11 ).each { printf ( "-- %5.2f\n" , [ it ] as float[] ) }
+ * ( 7..11 ).each { printf ( "-- %5.2g\n" , [ it ] as double[] ) }
+ * </pre>
+ *
+ * @param self any Object
+ * @param format A format string
+ * @param arg Argument which is referenced by the format specifiers in the format
+ * string. The type of <code>arg</code> should be one of Object[], List,
+ * int[], short[], byte[], char[], boolean[], long[], float[], or double[].
+ * @since 1.0
*/
- public static <T> Iterator<T> eachWithIndex(Iterator<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- final Object[] args = new Object[2];
- int counter = 0;
- while (self.hasNext()) {
- args[0] = self.next();
- args[1] = counter++;
- closure.call(args);
+ public static void printf(Object self, String format, Object arg) {
+ if (self instanceof PrintStream)
+ printf((PrintStream) self, format, arg);
+ else if (self instanceof Writer)
+ printf((Writer) self, format, arg);
+ else
+ printf(System.out, format, arg);
+ }
+
+ private static void printf(PrintStream self, String format, Object arg) {
+ self.print(sprintf(self, format, arg));
+ }
+
+ private static void printf(Writer self, String format, Object arg) {
+ try {
+ self.write(sprintf(self, format, arg));
+ } catch (IOException e) {
+ printf(System.out, format, arg);
}
- return self;
}
/**
- * Iterates through a Collection,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Sprintf to a string.
*
- * @param self a Collection
- * @param closure a Closure to operate on each item
- * @return the self Collection
- * @since 2.4.0
+ * @param self any Object
+ * @param format a format string
+ * @param values values referenced by the format specifiers in the format string
+ * @return the resulting formatted string
+ * @since 1.5.0
*/
- public static <T> Collection<T> eachWithIndex(Collection<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- return (Collection<T>) eachWithIndex((Iterable<T>) self, closure);
+ public static String sprintf(Object self, String format, Object[] values) {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream out = new PrintStream(outputStream);
+ out.printf(format, values);
+ return outputStream.toString();
}
/**
- * Iterates through a List,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Returns a formatted string using the specified format string and
+ * arguments.
*
- * @param self a List
- * @param closure a Closure to operate on each item
- * @return the self List
- * @since 2.4.0
+ * @param self any Object
+ * @param format A format string
+ * @param arg Argument which is referenced by the format specifiers in the format
+ * string. The type of <code>arg</code> should be one of Object[], List,
+ * int[], short[], byte[], char[], boolean[], long[], float[], or double[].
+ * @return the resulting printf'd string
+ * @since 1.5.0
*/
- public static <T> List<T> eachWithIndex(List<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- return (List<T>) eachWithIndex((Iterable<T>) self, closure);
+ public static String sprintf(Object self, String format, Object arg) {
+ if (arg instanceof Object[]) {
+ return sprintf(self, format, (Object[]) arg);
+ }
+ if (arg instanceof List) {
+ return sprintf(self, format, ((List) arg).toArray());
+ }
+ if (!arg.getClass().isArray()) {
+ Object[] o = (Object[]) java.lang.reflect.Array.newInstance(arg.getClass(), 1);
+ o[0] = arg;
+ return sprintf(self, format, o);
+ }
+
+ Object[] ans;
+ String elemType = arg.getClass().getName();
+ switch (elemType) {
+ case "[I":
+ int[] ia = (int[]) arg;
+ ans = new Integer[ia.length];
+ for (int i = 0; i < ia.length; i++) {
+ ans[i] = ia[i];
+ }
+ break;
+ case "[C":
+ char[] ca = (char[]) arg;
+ ans = new Character[ca.length];
+ for (int i = 0; i < ca.length; i++) {
+ ans[i] = ca[i];
+ }
+ break;
+ case "[Z": {
+ boolean[] ba = (boolean[]) arg;
+ ans = new Boolean[ba.length];
+ for (int i = 0; i < ba.length; i++) {
+ ans[i] = ba[i];
+ }
+ break;
+ }
+ case "[B": {
+ byte[] ba = (byte[]) arg;
+ ans = new Byte[ba.length];
+ for (int i = 0; i < ba.length; i++) {
+ ans[i] = ba[i];
+ }
+ break;
+ }
+ case "[S":
+ short[] sa = (short[]) arg;
+ ans = new Short[sa.length];
+ for (int i = 0; i < sa.length; i++) {
+ ans[i] = sa[i];
+ }
+ break;
+ case "[F":
+ float[] fa = (float[]) arg;
+ ans = new Float[fa.length];
+ for (int i = 0; i < fa.length; i++) {
+ ans[i] = fa[i];
+ }
+ break;
+ case "[J":
+ long[] la = (long[]) arg;
+ ans = new Long[la.length];
+ for (int i = 0; i < la.length; i++) {
+ ans[i] = la[i];
+ }
+ break;
+ case "[D":
+ double[] da = (double[]) arg;
+ ans = new Double[da.length];
+ for (int i = 0; i < da.length; i++) {
+ ans[i] = da[i];
+ }
+ break;
+ default:
+ throw new RuntimeException("sprintf(String," + arg + ")");
+ }
+ return sprintf(self, format, ans);
}
+ //-------------------------------------------------------------------------
+ // isCase/isNotCase
+
/**
- * Iterates through a Set,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Method for overloading the behavior of the 'case' method in switch statements.
+ * The default implementation handles arrays types but otherwise simply delegates
+ * to Object#equals, but this may be overridden for other types. In this example:
+ * <pre> switch( a ) {
+ * case b: //some code
+ * }</pre>
+ * "some code" is called when <code>b.isCase( a )</code> returns
+ * <code>true</code>.
*
- * @param self a Set
- * @param closure a Closure to operate on each item
- * @return the self Set
- * @since 2.4.0
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return true if the switchValue is deemed to be equal to the caseValue
+ * @since 1.0
*/
- public static <T> Set<T> eachWithIndex(Set<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- return (Set<T>) eachWithIndex((Iterable<T>) self, closure);
+ public static boolean isCase(Object caseValue, Object switchValue) {
+ if (caseValue.getClass().isArray()) {
+ return isCase(DefaultTypeTransformation.asCollection(caseValue), switchValue);
+ }
+ return caseValue.equals(switchValue);
}
/**
- * Iterates through a SortedSet,
- * passing each item and the item's index (a counter starting at
- * zero) to the given closure.
+ * Special 'Case' implementation for Class, which allows testing
+ * whether some switch value is assignable from the given case class.
*
- * @param self a SortedSet
- * @param closure a Closure to operate on each item
- * @return the self SortedSet
- * @since 2.4.0
+ * If the switch value is an object, {@code isCase} will return true if the
+ * switch value is assignment compatible with the class (case value),
+ * i.e. is an {@code instanceof} the class, for example:
+ * <pre class="groovyTestCase">
+ * def someList = []
+ * switch (someList) {
+ * case List:
+ * assert true : 'is a list'
+ * break
+ * case Map:
+ * assert false : 'is not a Map'
+ * break
+ * default:
+ * assert false : 'should never get here'
+ * break
+ * }
+ * </pre>
+ *
+ * If the switch value is a class, {@code isCase} will return true if the
+ * switch value is assignable from the given class (case value), i.e. the case class
+ * is the same as, or a superclass, or a super-interface of the switch class, for example:
+ * <pre class="groovyTestCase">
+ * switch (ArrayList) {
+ * case List:
+ * assert true : 'is a list'
+ * break
+ * case Map:
+ * assert false : 'is not a Map'
+ * break
+ * default:
+ * assert false : 'should never get here'
+ * break
+ * }
+ * </pre>
+ *
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return true if the switchValue is deemed to be assignable from the given class
+ * @since 1.0
*/
- public static <T> SortedSet<T> eachWithIndex(SortedSet<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
- return (SortedSet<T>) eachWithIndex((Iterable<T>) self, closure);
+ @SuppressWarnings("unchecked")
+ public static boolean isCase(Class caseValue, Object switchValue) {
+ if (switchValue instanceof Class) {
+ Class val = (Class) switchValue;
+ return caseValue.isAssignableFrom(val);
+ }
+ return caseValue.isInstance(switchValue);
}
/**
- * Iterates through an Iterable, passing each item to the given closure.
+ * 'Case' implementation for collections which tests if the 'switch'
+ * operand is contained in any of the 'case' values.
+ * For example:
+ * <pre class="groovyTestCase">switch( 3 ) {
+ * case [1,3,5]:
+ * assert true
+ * break
+ * default:
+ * assert false
+ * }</pre>
*
- * @param self the Iterable over which we iterate
- * @param closure the closure applied on each element found
- * @return the self Iterable
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return true if the caseValue is deemed to contain the switchValue
+ * @see java.util.Collection#contains(java.lang.Object)
+ * @since 1.0
*/
- public static <T> Iterable<T> each(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- each(self.iterator(), closure);
- return self;
+ public static boolean isCase(Collection caseValue, Object switchValue) {
+ return caseValue.contains(switchValue);
}
/**
- * Iterates through an Iterator, passing each item to the given closure.
+ * 'Case' implementation for iterable types which tests if the 'switch'
+ * operand is contained in any of the 'case' values.
+ * For example:
+ * <pre class="groovyTestCase">Iterable it = {[1,3,5].iterator()}
+ * switch( 3 ) {
+ * case it:
+ * assert true
+ * break
+ * default:
+ * assert false
+ * }
*
- * @param self the Iterator over which we iterate
- * @param closure the closure applied on each element found
- * @return the self Iterator
- * @since 2.4.0
+ * //GROOVY-7919
+ * assert 1 in it
+ * assert 2 !in it
+ * </pre>
+ *
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return true if the caseValue is deemed to contain the switchValue
+ * @see #contains(Iterable,Object)
+ * @since 5.0.0
*/
- public static <T> Iterator<T> each(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- while (self.hasNext()) {
- Object arg = self.next();
- closure.call(arg);
- }
- return self;
+ public static boolean isCase(Iterable caseValue, Object switchValue) {
+ return contains(caseValue, switchValue);
}
/**
- * Iterates through a Collection, passing each item to the given closure.
+ * 'Case' implementation for maps which tests the groovy truth
+ * value obtained using the 'switch' operand as key.
+ * For example:
+ * <pre class="groovyTestCase">switch( 'foo' ) {
+ * case [foo:true, bar:false]:
+ * assert true
+ * break
+ * default:
+ * assert false
+ * }</pre>
*
- * @param self the Collection over which we iterate
- * @param closure the closure applied on each element found
- * @return the self Collection
- * @since 2.4.0
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return the groovy truth value from caseValue corresponding to the switchValue key
+ * @since 1.7.6
*/
- public static <T> Collection<T> each(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (Collection<T>) each((Iterable<T>) self, closure);
+ public static boolean isCase(Map caseValue, Object switchValue) {
+ return DefaultTypeTransformation.castToBoolean(caseValue.get(switchValue));
}
/**
- * Iterates through a List, passing each item to the given closure.
+ * Special 'case' implementation for all numbers, which delegates to the
+ * <code>compareTo()</code> method for comparing numbers of different
+ * types.
*
- * @param self the List over which we iterate
- * @param closure the closure applied on each element found
- * @return the self List
- * @since 2.4.0
+ * @param caseValue the case value
+ * @param switchValue the switch value
+ * @return true if the numbers are deemed equal
+ * @since 1.5.0
*/
- public static <T> List<T> each(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (List<T>) each((Iterable<T>) self, closure);
+ public static boolean isCase(Number caseValue, Number switchValue) {
+ return NumberMath.compareTo(caseValue, switchValue) == 0;
}
/**
- * Iterates through a Set, passing each item to the given closure.
- *
- * @param self the Set over which we iterate
- * @param closure the closure applied on each element found
- * @return the self Set
- * @since 2.4.0
+ * @since 4.0.0
*/
- public static <T> Set<T> each(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (Set<T>) each((Iterable<T>) self, closure);
+ public static boolean isNotCase(Number caseValue, Number switchValue) {
+ return !isCase(caseValue, switchValue);
}
/**
- * Iterates through a SortedSet, passing each item to the given closure.
- *
- * @param self the SortedSet over which we iterate
- * @param closure the closure applied on each element found
- * @return the self SortedSet
- * @since 2.4.0
+ * @since 4.0.0
*/
- public static <T> SortedSet<T> each(SortedSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (SortedSet<T>) each((Iterable<T>) self, closure);
+ public static boolean isNotCase(Object caseValue, Object switchValue) {
+ return !isCase(caseValue, switchValue);
}
/**
- * Allows a Map to be iterated through using a closure. If the
- * closure takes one parameter then it will be passed the Map.Entry
- * otherwise if the closure takes two parameters then it will be
- * passed the key and the value.
- * <pre class="groovyTestCase">def result = ""
- * [a:1, b:3].each { key, value {@code ->} result += "$key$value" }
- * assert result == "a1b3"</pre>
- * <pre class="groovyTestCase">def result = ""
- * [a:1, b:3].each { entry {@code ->} result += entry }
- * assert result == "a=1b=3"</pre>
- *
- * In general, the order in which the map contents are processed
- * cannot be guaranteed. In practise, specialized forms of Map,
- * e.g. a TreeMap will have its contents processed according to
- * the natural ordering of the map.
- *
- * @param self the map over which we iterate
- * @param closure the 1 or 2 arg closure applied on each entry of the map
- * @return returns the self parameter
- * @since 1.5.0
+ * @since 4.0.0
*/
- public static <K, V> Map<K, V> each(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
- for (Map.Entry<K, V> entry : self.entrySet()) {
- callClosureForMapEntry(closure, entry);
- }
- return self;
+ public static boolean isNotCase(Class<?> caseValue, Object switchValue) {
+ return !isCase(caseValue, switchValue);
}
/**
- * Allows a Map to be iterated through in reverse order using a closure.
- *
- * In general, the order in which the map contents are processed
- * cannot be guaranteed. In practise, specialized forms of Map,
- * e.g. a TreeMap will have its contents processed according to the
- * reverse of the natural ordering of the map.
- *
- * @param self the map over which we iterate
- * @param closure the 1 or 2 arg closure applied on each entry of the map
- * @return returns the self parameter
- * @see #each(Map, Closure)
- * @since 1.7.2
+ * @since 4.0.0
*/
- @SuppressWarnings("unchecked")
- public static <K, V> Map<K, V> reverseEach(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
- final Iterator<Map.Entry<K, V>> entries = reverse(self.entrySet().iterator());
- while (entries.hasNext()) {
- callClosureForMapEntry(closure, entries.next());
- }
- return self;
+ public static boolean isNotCase(Closure<?> caseValue, Object switchValue) {
+ return !caseValue.isCase(switchValue);
}
/**
- * Allows a Map to be iterated through using a closure. If the
- * closure takes two parameters then it will be passed the Map.Entry and
- * the item's index (a counter starting at zero) otherwise if the closure
- * takes three parameters then it will be passed the key, the value, and
- * the index.
- * <pre class="groovyTestCase">def result = ""
- * [a:1, b:3].eachWithIndex { key, value, index {@code ->} result += "$index($key$value)" }
- * assert result == "0(a1)1(b3)"</pre>
- * <pre class="groovyTestCase">def result = ""
- * [a:1, b:3].eachWithIndex { entry, index {@code ->} result += "$index($entry)" }
- * assert result == "0(a=1)1(b=3)"</pre>
- *
- * @param self the map over which we iterate
- * @param closure a 2 or 3 arg Closure to operate on each item
- * @return the self Object
- * @since 1.5.0
+ * @since 4.0.0
*/
- public static <K, V> Map<K, V> eachWithIndex(Map<K, V> self, @ClosureParams(value=MapEntryOrKeyValue.class, options="index=true") Closure<?> closure) {
- int counter = 0;
- for (Map.Entry<K, V> entry : self.entrySet()) {
- callClosureForMapEntryAndCounter(closure, entry, counter++);
- }
- return self;
+ public static boolean isNotCase(Collection<?> caseValue, Object switchValue) {
+ return !isCase(caseValue, switchValue);
}
/**
- * Iterate over each element of the list in the reverse order.
- * <pre class="groovyTestCase">def result = []
- * [1,2,3].reverseEach { result << it }
- * assert result == [3,2,1]</pre>
- *
- * @param self a List
- * @param closure a closure to which each item is passed.
- * @return the original list
- * @since 1.5.0
+ * @since 4.0.0
*/
- public static <T> List<T> reverseEach(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- each(new ReverseListIterator<>(self), closure);
- return self;
+ public static boolean isNotCase(Map<?, ?> caseValue, Object switchValue) {
+ return !isCase(caseValue, switchValue);
}
+ //--------------------------------------------------------------------------
+
/**
- * Iterate over each element of the set in reverse order.
- * <pre class="groovyTestCase">
- * TreeSet navSet = [2, 4, 1, 3] // natural order is sorted
- * List result = []
- * navSet.reverseEach { result << it }
- * assert result == [4, 3, 2, 1]
- * </pre>
+ * Returns an iterator equivalent to this iterator with all duplicated items removed
+ * by using Groovy's default number-aware comparator. The original iterator will become
+ * exhausted of elements after determining the unique values. A new iterator
+ * for the unique values will be returned.
*
- * @param self a NavigableSet
- * @param closure a closure to which each item is passed.
- * @return the original NavigableSet
- * @since 4.0.11
+ * @param self an Iterator
+ * @return a new Iterator of the unique items from the original iterator
+ * @since 1.5.5
*/
- public static <T> NavigableSet<T> reverseEach(NavigableSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- each(self.descendingIterator(), closure);
- return self;
+ public static <T> Iterator<T> unique(Iterator<T> self) {
+ return uniqueItems(new IteratorIterableAdapter<>(self)).listIterator();
}
/**
- * Used to determine if the given predicate closure is valid (i.e. returns
- * <code>true</code> for all items in this data structure).
- * A simple example for a list:
- * <pre>def list = [3,4,5]
- * def greaterThanTwo = list.every { it {@code >} 2 }
- * </pre>
+ * Modifies this collection to remove all duplicated items, using Groovy's
+ * default number-aware comparator.
+ * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
*
- * @param self the object over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if every iteration of the object matches the closure predicate
+ * @param self a collection
+ * @return the now modified collection
+ * @see #unique(Collection, boolean)
* @since 1.0
*/
- public static boolean every(Object self, Closure predicate) {
- return every(InvokerHelper.asIterator(self), predicate);
+ public static <T> Collection<T> unique(Collection<T> self) {
+ return unique(self, true);
}
/**
- * Used to determine if the given predicate closure is valid (i.e. returns
- * <code>true</code> for all items in this iterator).
- * A simple example for a list:
- * <pre>def list = [3,4,5]
- * def greaterThanTwo = list.iterator().every { it {@code >} 2 }
- * </pre>
+ * Modifies this List to remove all duplicated items, using Groovy's
+ * default number-aware comparator.
+ * <pre class="groovyTestCase">assert [1,3] == [1,3,3].unique()</pre>
*
- * @param self the iterator over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if every iteration of the object matches the closure predicate
- * @since 2.3.0
+ * @param self a List
+ * @return the now modified List
+ * @see #unique(Collection, boolean)
+ * @since 2.4.0
*/
- public static <T> boolean every(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
- while (self.hasNext()) {
- if (!bcw.call(self.next())) {
- return false;
- }
- }
- return true;
+ public static <T> List<T> unique(List<T> self) {
+ return (List<T>) unique((Collection<T>) self, true);
}
/**
- * Used to determine if the given predicate closure is valid (i.e. returns
- * <code>true</code> for all items in this iterable).
- * A simple example for a list:
- * <pre>def list = [3,4,5]
- * def greaterThanTwo = list.every { it {@code >} 2 }
+ * Remove all duplicates from a given Collection using Groovy's default number-aware comparator.
+ * If mutate is true, it works by modifying the original object (and also returning it).
+ * If mutate is false, a new collection is returned leaving the original unchanged.
+ * <pre class="groovyTestCase">
+ * assert [1,3] == [1,3,3].unique()
+ * </pre>
+ * <pre class="groovyTestCase">
+ * def orig = [1, 3, 2, 3]
+ * def uniq = orig.unique(false)
+ * assert orig == [1, 3, 2, 3]
+ * assert uniq == [1, 3, 2]
* </pre>
*
- * @param self the iterable over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if every iteration of the object matches the closure predicate
- * @since 2.3.0
+ * @param self a collection
+ * @param mutate false will cause a new list containing unique items from the collection to be created, true will mutate collections in place
+ * @return the now modified collection
+ * @since 1.8.1
*/
- public static <T> boolean every(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
- return every(self.iterator(), predicate);
+ public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
+ List<T> answer = uniqueItems(self);
+ if (mutate) {
+ self.clear();
+ self.addAll(answer);
+ }
+ return mutate ? self : answer ;
}
- /**
- * Iterates over the entries of a map, and checks whether a predicate is
- * valid for all entries. If the
- * closure takes one parameter then it will be passed the Map.Entry
- * otherwise if the closure takes two parameters then it will be
- * passed the key and the value.
- * <pre class="groovyTestCase">def map = [a:1, b:2.0, c:2L]
- * assert !map.every { key, value {@code ->} value instanceof Integer }
- * assert map.every { entry {@code ->} entry.value instanceof Number }</pre>
- *
- * @param self the map over which we iterate
- * @param predicate the 1 or 2 arg Closure predicate used for matching
- * @return true if every entry of the map matches the closure predicate
- * @since 1.5.0
- */
- public static <K, V> boolean every(Map<K, V> self, @ClosureParams(value = MapEntryOrKeyValue.class) Closure predicate) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (!bcw.callForMap(entry)) {
- return false;
+ private static <T> List<T> uniqueItems(Iterable<T> self) {
+ List<T> answer = new ArrayList<>();
+ for (T t : self) {
+ boolean duplicated = false;
+ for (T t2 : answer) {
+ if (coercedEquals(t, t2)) {
+ duplicated = true;
+ break;
+ }
}
+ if (!duplicated)
+ answer.add(t);
}
- return true;
+ return answer;
}
/**
- * Iterates over every element of a collection, and checks whether all
- * elements are <code>true</code> according to the Groovy Truth.
- * Equivalent to <code>self.every({element {@code ->} element})</code>
+ * Remove all duplicates from a given List using Groovy's default number-aware comparator.
+ * If mutate is true, it works by modifying the original object (and also returning it).
+ * If mutate is false, a new collection is returned leaving the original unchanged.
* <pre class="groovyTestCase">
- * assert [true, true].every()
- * assert [1, 1].every()
- * assert ![1, 0].every()
+ * assert [1,3] == [1,3,3].unique()
+ * </pre>
+ * <pre class="groovyTestCase">
+ * def orig = [1, 3, 2, 3]
+ * def uniq = orig.unique(false)
+ * assert orig == [1, 3, 2, 3]
+ * assert uniq == [1, 3, 2]
* </pre>
*
- * @param self the object over which we iterate
- * @return true if every item in the collection matches satisfies Groovy truth
- * @since 1.5.0
+ * @param self a List
+ * @param mutate false will cause a new List containing unique items from the List to be created, true will mutate List in place
+ * @return the now modified List
+ * @since 2.4.0
*/
- public static boolean every(Object self) {
- BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
- if (!bmi.convertToBoolean(iter.next())) {
- return false;
- }
- }
- return true;
+ public static <T> List<T> unique(List<T> self, boolean mutate) {
+ return (List<T>) unique((Collection<T>) self, mutate);
}
/**
- * Iterates over the contents of an object or collection, and checks whether a
- * predicate is valid for at least one element.
- * <pre class="groovyTestCase">
- * assert [1, 2, 3].any { it == 2 }
- * assert ![1, 2, 3].any { it {@code >} 3 }
- * </pre>
+ * Provides a method that compares two comparables using Groovy's
+ * default number aware comparator.
*
- * @param self the object over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if any iteration for the object matches the closure predicate
- * @since 1.0
+ * @param self a Comparable
+ * @param other another Comparable
+ * @return a -ve number, 0 or a +ve number according to Groovy's compareTo contract
+ * @since 1.6.0
*/
- public static boolean any(Object self, Closure predicate) {
- return any(InvokerHelper.asIterator(self), predicate);
+ public static int numberAwareCompareTo(Comparable self, Comparable other) {
+ return COMPARABLE_NUMBER_AWARE_COMPARATOR.compare(self, other);
}
/**
- * Iterates over the contents of an iterator, and checks whether a
- * predicate is valid for at least one element.
- * <pre class="groovyTestCase">
- * assert [1, 2, 3].iterator().any { it == 2 }
- * assert ![1, 2, 3].iterator().any { it {@code >} 3 }
- * </pre>
+ * Returns an iterator equivalent to this iterator but with all duplicated items
+ * removed by using a Closure to determine duplicate (equal) items.
+ * The original iterator will be fully processed after the call.
+ * <p>
+ * If the closure takes a single parameter, the argument passed will be each element,
+ * and the closure should return a value used for comparison (either using
+ * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
+ * If the closure takes two parameters, two items from the Iterator
+ * will be passed as arguments, and the closure should return an
+ * int value (with 0 indicating the items are not unique).
*
- * @param self the iterator over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if any iteration for the object matches the closure predicate
- * @since 1.0
+ * @param self an Iterator
+ * @param condition a Closure used to determine unique items
+ * @return the modified Iterator
+ * @since 1.5.5
*/
- public static <T> boolean any(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
- while (self.hasNext()) {
- if (bcw.call(self.next())) return true;
- }
- return false;
+ public static <T> Iterator<T> unique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
+ Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
+ ? new OrderBy<>(condition, true)
+ : new ClosureComparator<>(condition);
+ return unique(self, comparator);
}
/**
- * Iterates over the contents of an iterable, and checks whether a
- * predicate is valid for at least one element.
- * <pre class="groovyTestCase">
- * assert [1, 2, 3].any { it == 2 }
- * assert ![1, 2, 3].any { it {@code >} 3 }
- * </pre>
+ * A convenience method for making a collection unique using a Closure
+ * to determine duplicate (equal) items.
+ * <p>
+ * If the closure takes a single parameter, the
+ * argument passed will be each element, and the closure
+ * should return a value used for comparison (either using
+ * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
+ * If the closure takes two parameters, two items from the collection
+ * will be passed as arguments, and the closure should return an
+ * int value (with 0 indicating the items are not unique).
+ * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
+ * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b {@code ->} a {@code <=>} b }</pre>
*
- * @param self the iterable over which we iterate
- * @param predicate the closure predicate used for matching
- * @return true if any iteration for the object matches the closure predicate
+ * @param self a Collection
+ * @param closure a 1 or 2 arg Closure used to determine unique items
+ * @return self without any duplicates
+ * @see #unique(Collection, boolean, Closure)
* @since 1.0
*/
- public static <T> boolean any(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
- return any(self.iterator(), predicate);
+ public static <T> Collection<T> unique(Collection<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
+ return unique(self, true, closure);
}
/**
- * Iterates over the entries of a map, and checks whether a predicate is
- * valid for at least one entry. If the
- * closure takes one parameter then it will be passed the Map.Entry
- * otherwise if the closure takes two parameters then it will be
- * passed the key and the value.
- * <pre class="groovyTestCase">
- * assert [2:3, 4:5, 5:10].any { key, value {@code ->} key * 2 == value }
- * assert ![2:3, 4:5, 5:10].any { entry {@code ->} entry.key == entry.value * 2 }
- * </pre>
+ * A convenience method for making a List unique using a Closure
+ * to determine duplicate (equal) items.
+ * <p>
+ * If the closure takes a single parameter, the
+ * argument passed will be each element, and the closure
+ * should return a value used for comparison (either using
+ * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
+ * If the closure takes two parameters, two items from the List
+ * will be passed as arguments, and the closure should return an
+ * int value (with 0 indicating the items are not unique).
+ * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].unique { it % 2 }</pre>
+ * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].unique { a, b {@code ->} a {@code <=>} b }</pre>
*
- * @param self the map over which we iterate
- * @param predicate the 1 or 2 arg closure predicate used for matching
- * @return true if any entry in the map matches the closure predicate
- * @since 1.5.0
+ * @param self a List
+ * @param closure a 1 or 2 arg Closure used to determine unique items
+ * @return self without any duplicates
+ * @see #unique(Collection, boolean, Closure)
+ * @since 2.4.0
*/
- public static <K, V> boolean any(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> predicate) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (bcw.callForMap(entry)) {
- return true;
- }
- }
- return false;
+ public static <T> List<T> unique(List<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
+ return (List<T>) unique((Collection<T>) self, true, closure);
}
/**
- * Iterates over the elements of a collection, and checks whether at least
- * one element is true according to the Groovy Truth.
- * Equivalent to self.any({element {@code ->} element})
+ * A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
+ * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
+ * <p>
+ * If the closure takes a single parameter, each element from the Collection will be passed to the closure. The closure
+ * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
+ * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
+ * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
* <pre class="groovyTestCase">
- * assert [false, true].any()
- * assert [0, 1].any()
- * assert ![0, 0].any()
+ * def orig = [1, 3, 4, 5]
+ * def uniq = orig.unique(false) { it % 2 }
+ * assert orig == [1, 3, 4, 5]
+ * assert uniq == [1, 4]
+ * </pre>
+ * <pre class="groovyTestCase">
+ * def orig = [2, 3, 3, 4]
+ * def uniq = orig.unique(false) { a, b {@code ->} a {@code <=>} b }
+ * assert orig == [2, 3, 3, 4]
+ * assert uniq == [2, 3, 4]
* </pre>
*
- * @param self the object over which we iterate
- * @return true if any item in the collection matches the closure predicate
- * @since 1.5.0
+ * @param self a Collection
+ * @param mutate false will always cause a new list to be created, true will mutate lists in place
+ * @param closure a 1 or 2 arg Closure used to determine unique items
+ * @return self without any duplicates
+ * @since 1.8.1
*/
- public static boolean any(Object self) {
- BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
- if (bmi.convertToBoolean(iter.next())) {
- return true;
- }
+ public static <T> Collection<T> unique(Collection<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
+ // use a comparator of one item or two
+ int params = closure.getMaximumNumberOfParameters();
+ if (params == 1) {
+ self = unique(self, mutate, new OrderBy<>(closure, true));
+ } else {
+ self = unique(self, mutate, new ClosureComparator<>(closure));
}
- return false;
+ return self;
}
/**
- * Iterates over the collection of items which this Object represents and returns each item that matches
- * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
- * method used by switch statements. This method can be used with different
- * kinds of filters like regular expressions, classes, ranges etc.
- * Example:
+ * A convenience method for making a List unique using a Closure to determine duplicate (equal) items.
+ * If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.
+ * <p>
+ * If the closure takes a single parameter, each element from the List will be passed to the closure. The closure
+ * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
+ * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the collection
+ * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
* <pre class="groovyTestCase">
- * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
- * assert list.grep( ~/a+/ ) == ['a', 'aa']
- * assert list.grep( ~/../ ) == ['aa', 'bc']
- * assert list.grep( Number ) == [ 3, 4.5 ]
- * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
+ * def orig = [1, 3, 4, 5]
+ * def uniq = orig.unique(false) { it % 2 }
+ * assert orig == [1, 3, 4, 5]
+ * assert uniq == [1, 4]
+ * </pre>
+ * <pre class="groovyTestCase">
+ * def orig = [2, 3, 3, 4]
+ * def uniq = orig.unique(false) { a, b {@code ->} a {@code <=>} b }
+ * assert orig == [2, 3, 3, 4]
+ * assert uniq == [2, 3, 4]
* </pre>
*
- * @param self the object over which we iterate
- * @param filter the filter to perform on the object (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
- * @return a collection of objects which match the filter
- * @since 1.5.6
+ * @param self a List
+ * @param mutate false will always cause a new list to be created, true will mutate lists in place
+ * @param closure a 1 or 2 arg Closure used to determine unique items
+ * @return self without any duplicates
+ * @since 2.4.0
*/
- @SuppressWarnings("unchecked")
- public static Collection grep(Object self, Object filter) {
- Collection answer = createSimilarOrDefaultCollection(self);
- BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
- Object object = iter.next();
- if (bmi.invoke(filter, object)) {
- answer.add(object);
- }
- }
- return answer;
+ public static <T> List<T> unique(List<T> self, boolean mutate, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure closure) {
+ return (List<T>) unique((Collection<T>) self, mutate, closure);
}
/**
- * Iterates over the collection of items and returns each item that matches
- * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
- * method used by switch statements. method can be used with different
- * kinds of filters like regular expressions, classes, ranges etc.
- * Example:
- * <pre class="groovyTestCase">
- * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
- * assert list.grep( ~/a+/ ) == ['a', 'aa']
- * assert list.grep( ~/../ ) == ['aa', 'bc']
- * assert list.grep( Number ) == [ 3, 4.5 ]
- * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
- * </pre>
+ * Returns an iterator equivalent to this iterator with all duplicated
+ * items removed by using the supplied comparator. The original iterator
+ * will be exhausted upon returning.
*
- * @param self a collection
- * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
- * @return a collection of objects which match the filter
- * @since 2.0
+ * @param self an Iterator
+ * @param comparator a Comparator
+ * @return the modified Iterator
+ * @since 1.5.5
*/
- public static <T> Collection<T> grep(Collection<T> self, Object filter) {
- Collection<T> answer = createSimilarCollection(self);
- BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
- for (T element : self) {
- if (bmi.invoke(filter, element)) {
- answer.add(element);
- }
+ public static <T> Iterator<T> unique(Iterator<T> self, Comparator<? super T> comparator) {
+ return uniqueItems(new IteratorIterableAdapter<>(self), comparator).listIterator();
+ }
+
+ private static final class IteratorIterableAdapter<T> implements Iterable<T> {
+ private final Iterator<T> self;
+
+ private IteratorIterableAdapter(Iterator<T> self) {
+ this.self = self;
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ return self;
}
- return answer;
}
/**
- * Iterates over the collection of items and returns each item that matches
- * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
- * method used by switch statements. This method can be used with different
- * kinds of filters like regular expressions, classes, ranges etc.
- * Example:
+ * Remove all duplicates from a given Collection.
+ * Works on the original object (and also returns it).
+ * The order of members in the Collection are compared by the given Comparator.
+ * For each duplicate, the first member which is returned
+ * by the given Collection's iterator is retained, but all other ones are removed.
+ * The given Collection's original order is preserved.
+ * <p>
* <pre class="groovyTestCase">
- * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
- * assert list.grep( ~/a+/ ) == ['a', 'aa']
- * assert list.grep( ~/../ ) == ['aa', 'bc']
- * assert list.grep( Number ) == [ 3, 4.5 ]
- * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
+ *
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.unique(new PersonComparator())
+ * assert( list2 == list {@code &&} list == [a, b, c] )
* </pre>
*
- * @param self a List
- * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
- * @return a List of objects which match the filter
- * @since 2.4.0
+ * @param self a Collection
+ * @param comparator a Comparator
+ * @return self the now modified collection without duplicates
+ * @see #unique(java.util.Collection, boolean, java.util.Comparator)
+ * @since 1.0
*/
- public static <T> List<T> grep(List<T> self, Object filter) {
- return (List<T>) grep((Collection<T>) self, filter);
+ public static <T> Collection<T> unique(Collection<T> self, Comparator<? super T> comparator) {
+ return unique(self, true, comparator) ;
}
/**
- * Iterates over the collection of items and returns each item that matches
- * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
- * method used by switch statements. This method can be used with different
- * kinds of filters like regular expressions, classes, ranges etc.
- * Example:
+ * Remove all duplicates from a given List.
+ * Works on the original object (and also returns it).
+ * The order of members in the List are compared by the given Comparator.
+ * For each duplicate, the first member which is returned
+ * by the given List's iterator is retained, but all other ones are removed.
+ * The given List's original order is preserved.
+ * <p>
* <pre class="groovyTestCase">
- * def set = ['a', 'b', 'aa', 'bc', 3, 4.5] as Set
- * assert set.grep( ~/a+/ ) == ['a', 'aa'] as Set
- * assert set.grep( ~/../ ) == ['aa', 'bc'] as Set
- * assert set.grep( Number ) == [ 3, 4.5 ] as Set
- * assert set.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ] as Set
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
+ *
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.unique(new PersonComparator())
+ * assert( list2 == list {@code &&} list == [a, b, c] )
* </pre>
*
- * @param self a Set
- * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
- * @return a Set of objects which match the filter
+ * @param self a List
+ * @param comparator a Comparator
+ * @return self the now modified List without duplicates
+ * @see #unique(java.util.Collection, boolean, java.util.Comparator)
* @since 2.4.0
*/
- public static <T> Set<T> grep(Set<T> self, Object filter) {
- return (Set<T>) grep((Collection<T>) self, filter);
+ public static <T> List<T> unique(List<T> self, Comparator<? super T> comparator) {
+ return (List<T>) unique((Collection<T>) self, true, comparator);
}
/**
- * Iterates over the collection of items which this Object represents and returns each item that matches
- * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * Remove all duplicates from a given Collection.
+ * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new collection is returned.
+ * The order of members in the Collection are compared by the given Comparator.
+ * For each duplicate, the first member which is returned
+ * by the given Collection's iterator is retained, but all other ones are removed.
+ * The given Collection's original order is preserved.
* <p>
- * Example:
* <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
+ *
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.unique(false, new PersonComparator())
+ * assert( list2 != list {@code &&} list2 == [a, b, c] )
* </pre>
*
- * @param self the object over which we iterate
- * @return a collection of objects which match the filter
+ * @param self a Collection
+ * @param mutate false will always cause a new collection to be created, true will mutate collections in place
+ * @param comparator a Comparator
+ * @return self the collection without duplicates
* @since 1.8.1
- * @see Closure#IDENTITY
*/
- public static Collection grep(Object self) {
- return grep(self, Closure.IDENTITY);
+ public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<? super T> comparator) {
+ List<T> answer = uniqueItems(self, comparator);
+ if (mutate) {
+ self.clear();
+ self.addAll(answer);
+ }
+ return mutate ? self : answer;
}
- /**
- * Iterates over the collection returning each element that matches
- * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
- * </pre>
- *
- * @param self a Collection
- * @return a collection of elements satisfy Groovy truth
- * @see Closure#IDENTITY
- * @since 2.0
- */
- public static <T> Collection<T> grep(Collection<T> self) {
- return grep(self, Closure.IDENTITY);
+ private static <T> List<T> uniqueItems(Iterable<T> self, Comparator<? super T> comparator) {
+ List<T> answer = new ArrayList<>();
+ for (T t : self) {
+ boolean duplicated = false;
+ for (T t2 : answer) {
+ if (comparator.compare(t, t2) == 0) {
+ duplicated = true;
+ break;
+ }
+ }
+ if (!duplicated)
+ answer.add(t);
+ }
+ return answer;
}
/**
- * Iterates over the collection returning each element that matches
- * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * Remove all duplicates from a given List.
+ * If mutate is true, it works on the original object (and also returns it). If mutate is false, a new List is returned.
+ * The order of members in the List are compared by the given Comparator.
+ * For each duplicate, the first member which is returned
+ * by the given List's iterator is retained, but all other ones are removed.
+ * The given List's original order is preserved.
* <p>
- * Example:
* <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
+ *
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.unique(false, new PersonComparator())
+ * assert( list2 != list {@code &&} list2 == [a, b, c] )
* </pre>
*
- * @param self a List
- * @return a List of elements satisfy Groovy truth
- * @see Closure#IDENTITY
+ * @param self a List
+ * @param mutate false will always cause a new List to be created, true will mutate List in place
+ * @param comparator a Comparator
+ * @return self the List without duplicates
* @since 2.4.0
*/
- public static <T> List<T> grep(List<T> self) {
- return grep(self, Closure.IDENTITY);
+ public static <T> List<T> unique(List<T> self, boolean mutate, Comparator<? super T> comparator) {
+ return (List<T>) unique((Collection<T>) self, mutate, comparator);
}
/**
- * Iterates over the collection returning each element that matches
- * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * Returns an iterator equivalent to this iterator but with all duplicated items
+ * removed where duplicate (equal) items are deduced by calling the supplied Closure condition.
* <p>
- * Example:
+ * If the supplied Closure takes a single parameter, the argument passed will be each element,
+ * and the closure should return a value used for comparison (either using
+ * {@link java.lang.Comparable#compareTo(java.lang.Object)} or {@link java.lang.Object#equals(java.lang.Object)}).
+ * If the closure takes two parameters, two items from the Iterator
+ * will be passed as arguments, and the closure should return an
+ * int value (with 0 indicating the items are not unique).
* <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
- * assert items.grep() == [1, 2, true, 'foo', [4, 5]] as Set
+ * def items = "Hello".toList() + [null, null] + "there".toList()
+ * def toLower = { it == null ? null : it.toLowerCase() }
+ * def noDups = items.iterator().toUnique(toLower).toList()
+ * assert noDups == ['H', 'e', 'l', 'o', null, 't', 'r']
* </pre>
+ * <pre class="groovyTestCase">assert [1,4] == [1,3,4,5].toUnique { it % 2 }</pre>
+ * <pre class="groovyTestCase">assert [2,3,4] == [2,3,3,4].toUnique { a, b {@code ->} a {@code <=>} b }</pre>
*
- * @param self a Set
- * @return a Set of elements satisfy Groovy truth
- * @see Closure#IDENTITY
+ * @param self an Iterator
+ * @param condition a Closure used to determine unique items
+ * @return an Iterator with no duplicate items
* @since 2.4.0
*/
- public static <T> Set<T> grep(Set<T> self) {
- return grep(self, Closure.IDENTITY);
+ public static <T> Iterator<T> toUnique(Iterator<T> self, @ClosureParams(value=FromString.class, options={"T","T,T"}) Closure condition) {
+ return toUnique(self, condition.getMaximumNumberOfParameters() == 1
+ ? new OrderBy<>(condition, true)
+ : new ClosureComparator<>(condition));
}
- /**
- * Counts the number of occurrences of the given value from the
- * items within this Iterator.
- * Comparison is done using Groovy's == operator (using
- * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
- * The iterator will become exhausted of elements after determining the count value.
- *
- * @param self the Iterator from which we count the number of matching occurrences
- * @param value the value being searched for
- * @return the number of occurrences
- * @since 1.5.0
- */
- public static Number count(Iterator self, Object value) {
- Objects.requireNonNull(self);
- long answer = 0;
- while (self.hasNext()) {
- if (DefaultTypeTransformation.compareEqual(self.next(), value)) {
- ++answer;
- }
- }
- // for b/c with Java return an int if we can
- if (answer <= Integer.MAX_VALUE) return (int) answer;
- return answer;
- }
+ private static final class ToUniqueIterator<E> implements Iterator<E> {
+ private final Iterator<E> delegate;
+ private final Set<E> seen;
+ private boolean exhausted;
+ private E next;
- /**
- * Counts the number of occurrences which satisfy the given closure from the
- * items within this Iterator.
- * The iterator will become exhausted of elements after determining the count value.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2</pre>
- *
- * @param self the Iterator from which we count the number of matching occurrences
- * @param closure a closure condition
- * @return the number of occurrences
- * @since 1.8.0
- */
- public static <T> Number count(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- long answer = 0;
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- while (self.hasNext()) {
- if (bcw.call(self.next())) {
- ++answer;
- }
+ private ToUniqueIterator(Iterator<E> delegate, Comparator<? super E> comparator) {
+ this.seen = new TreeSet<>(comparator);
+ this.delegate = delegate;
+ advance();
}
- // for b/c with Java return an int if we can
- if (answer <= Integer.MAX_VALUE) return (int) answer;
- return answer;
- }
-
- /**
- * Counts the number of occurrences of the given value inside this Iterable.
- * Comparison is done using Groovy's == operator (using
- * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count(4) == 2</pre>
- *
- * @param self the Iterable within which we count the number of occurrences
- * @param value the value being searched for
- * @return the number of occurrences
- * @since 2.2.0
- */
- public static Number count(Iterable self, Object value) {
- return count(self.iterator(), value);
- }
- /**
- * Counts the number of occurrences which satisfy the given closure from inside this Iterable.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5</pre>
- *
- * @param self the Iterable within which we count the number of occurrences
- * @param closure a closure condition
- * @return the number of occurrences
- * @since 2.2.0
- */
- public static <T> Number count(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return count(self.iterator(), closure);
- }
+ @Override
+ public boolean hasNext() {
+ return !exhausted;
+ }
- /**
- * Counts the number of occurrences which satisfy the given closure from inside this map.
- * If the closure takes one parameter then it will be passed the Map.Entry.
- * Otherwise, the closure should take two parameters and will be passed the key and value.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [a:1, b:1, c:2, d:2].count{ k,v {@code ->} k == 'a' {@code ||} v == 2 } == 3</pre>
- *
- * @param self the map within which we count the number of occurrences
- * @param closure a 1 or 2 arg Closure condition applying on the entries
- * @return the number of occurrences
- * @since 1.8.0
- */
- public static <K,V> Number count(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
- long answer = 0;
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (bcw.callForMap(entry)) {
- ++answer;
- }
+ @Override
+ public E next() {
+ if (exhausted) throw new NoSuchElementException();
+ E result = next;
+ advance();
+ return result;
}
- // for b/c with Java return an int if we can
- if (answer <= Integer.MAX_VALUE) return (int) answer;
- return answer;
- }
- /**
- * Convert an iterator to a List. The iterator will become
- * exhausted of elements after making this conversion.
- *
- * @param self an iterator
- * @return a List
- * @since 1.5.0
- */
- public static <T> List<T> toList(Iterator<T> self) {
+ @Override
+ public void remove() {
+ if (exhausted) throw new NoSuchElementException();
+ delegate.remove();
+ }
- List<T> answer = new ArrayList<>();
- while (self.hasNext()) {
- answer.add(self.next());
+ private void advance() {
+ boolean foundNext = false;
+ while (!foundNext && !exhausted) {
+ exhausted = !delegate.hasNext();
+ if (!exhausted) {
+ next = delegate.next();
+ foundNext = seen.add(next);
+ }
+ }
}
- return answer;
}
/**
- * Convert an Iterable to a List. The Iterable's iterator will
- * become exhausted of elements after making this conversion.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">def x = [1,2,3] as HashSet
- * assert x.class == HashSet
- * assert x.toList() instanceof List</pre>
+ * Returns an iterator equivalent to this iterator with all duplicated
+ * items removed by using the supplied comparator.
*
- * @param self an Iterable
- * @return a List
- * @since 1.8.7
+ * @param self an Iterator
+ * @param comparator a Comparator used to determine unique (equal) items
+ * If {@code null}, the Comparable natural ordering of the elements will be used.
+ * @return an Iterator with no duplicate items
+ * @since 2.4.0
*/
- public static <T> List<T> toList(Iterable<T> self) {
- return toList(self.iterator());
+ public static <T> Iterator<T> toUnique(Iterator<T> self, Comparator<? super T> comparator) {
+ return new ToUniqueIterator<>(self, comparator);
}
/**
- * Convert an enumeration to a List.
+ * Returns an iterator equivalent to this iterator with all duplicated
+ * items removed by using the natural ordering of the items.
*
- * @param self an enumeration
- * @return a List
- * @since 1.5.0
+ * @param self an Iterator
+ * @return an Iterator with no duplicate items
+ * @since 2.4.0
*/
- public static <T> List<T> toList(Enumeration<T> self) {
- List<T> answer = new ArrayList<>();
- while (self.hasMoreElements()) {
- answer.add(self.nextElement());
- }
- return answer;
+ public static <T> Iterator<T> toUnique(Iterator<T> self) {
+ return toUnique(self, (Comparator<T>) null);
}
/**
- * Collates this iterable into sub-lists of length <code>size</code>.
- * Example:
- * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
- * def coll = list.collate( 3 )
- * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]</pre>
+ * Returns a Collection containing the items from the Iterable but with duplicates removed.
+ * The items in the Iterable are compared by the given Comparator.
+ * For each duplicate, the first member which is returned from the
+ * Iterable is retained, but all other ones are removed.
+ * <p>
+ * <pre class="groovyTestCase">
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
*
- * @param self an Iterable
- * @param size the length of each sub-list in the returned list
- * @return a List containing the data collated into sub-lists
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.toUnique(new PersonComparator())
+ * assert list2 == [a, b, c] {@code &&} list == [a, b, c, d]
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param comparator a Comparator used to determine unique (equal) items
+ * If {@code null}, the Comparable natural ordering of the elements will be used.
+ * @return the Collection of non-duplicate items
* @since 2.4.0
*/
- public static <T> List<List<T>> collate(Iterable<T> self, int size) {
- return collate(self, size, true);
+ public static <T> Collection<T> toUnique(Iterable<T> self, Comparator<? super T> comparator) {
+ Collection<T> result = createSimilarCollection(self);
+ addAll(result, toUnique(self.iterator(), comparator));
+ return result;
}
/**
- * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
- * elements for each subList.
- * Example:
- * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4 ]
- * def coll = list.collate( 3, 1 )
- * assert coll == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]</pre>
+ * Returns a List containing the items from the List but with duplicates removed.
+ * The items in the List are compared by the given Comparator.
+ * For each duplicate, the first member which is returned from the
+ * List is retained, but all other ones are removed.
+ * <p>
+ * <pre class="groovyTestCase">
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
*
- * @param self an Iterable
- * @param size the length of each sub-list in the returned list
- * @param step the number of elements to step through for each sub-list
- * @return a List containing the data collated into sub-lists
+ * class PersonComparator implements Comparator {
+ * int compare(Object o1, Object o2) {
+ * Person p1 = (Person) o1
+ * Person p2 = (Person) o2
+ * if (p1.lname != p2.lname)
+ * return p1.lname.compareTo(p2.lname)
+ * else
+ * return p1.fname.compareTo(p2.fname)
+ * }
+ *
+ * boolean equals(Object obj) {
+ * return this.equals(obj)
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * List list2 = list.toUnique(new PersonComparator())
+ * assert list2 == [a, b, c] {@code &&} list == [a, b, c, d]
+ * </pre>
+ *
+ * @param self a List
+ * @param comparator a Comparator used to determine unique (equal) items
+ * If {@code null}, the Comparable natural ordering of the elements will be used.
+ * @return the List of non-duplicate items
* @since 2.4.0
*/
- public static <T> List<List<T>> collate(Iterable<T> self, int size, int step) {
- return collate(self, size, step, true);
+ public static <T> List<T> toUnique(List<T> self, Comparator<? super T> comparator) {
+ return (List<T>) toUnique((Iterable<T>) self, comparator);
}
/**
- * Collates this iterable into sub-lists of length <code>size</code>. Any remaining elements in
- * the iterable after the subdivision will be dropped if <code>keepRemainder</code> is false.
- * Example:
- * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
- * def coll = list.collate( 3, false )
- * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]</pre>
+ * Returns a Collection containing the items from the Iterable but with duplicates removed
+ * using the natural ordering of the items to determine uniqueness.
+ * <p>
+ * <pre class="groovyTestCase">
+ * String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
+ * String[] expected = ['c', 'a', 't', 's', 'h']
+ * assert letters.toUnique() == expected
+ * </pre>
*
- * @param self an Iterable
- * @param size the length of each sub-list in the returned list
- * @param keepRemainder if true, any remaining elements are returned as sub-lists. Otherwise they are discarded
- * @return a List containing the data collated into sub-lists
+ * @param self an Iterable
+ * @return the Collection of non-duplicate items
* @since 2.4.0
*/
- public static <T> List<List<T>> collate(Iterable<T> self, int size, boolean keepRemainder) {
- return collate(self, size, size, keepRemainder);
+ public static <T> Collection<T> toUnique(Iterable<T> self) {
+ return toUnique(self, (Comparator<T>) null);
}
/**
- * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
- * elements for each sub-list. Any remaining elements in the iterable after the subdivision will be dropped if
- * <code>keepRemainder</code> is false.
- * Example:
+ * Returns a List containing the items from the List but with duplicates removed
+ * using the natural ordering of the items to determine uniqueness.
+ * <p>
* <pre class="groovyTestCase">
- * def list = [ 1, 2, 3, 4 ]
- * assert list.collate( 2, 2, true ) == [ [ 1, 2 ], [ 3, 4 ] ]
- * assert list.collate( 3, 1, true ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
- * assert list.collate( 3, 1, false ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ] ]
+ * def letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't']
+ * def expected = ['c', 'a', 't', 's', 'h']
+ * assert letters.toUnique() == expected
* </pre>
*
- * @param self an Iterable
- * @param size the length of each sub-list in the returned list
- * @param step the number of elements to step through for each sub-list
- * @param keepRemainder if true, any remaining elements are returned as sub-lists. Otherwise they are discarded
- * @return a List containing the data collated into sub-lists
- * @throws IllegalArgumentException if the step is zero.
+ * @param self a List
+ * @return the List of non-duplicate items
* @since 2.4.0
*/
- public static <T> List<List<T>> collate(Iterable<T> self, int size, int step, boolean keepRemainder) {
- final List<T> selfList = asList(self);
- final List<List<T>> answer;
- if (size <= 0) {
- answer = new ArrayList<>(1);
- answer.add(selfList);
- } else {
- if (step == 0) throw new IllegalArgumentException("step cannot be zero");
- final int selfListSize = selfList.size();
- answer = new ArrayList<>(step < 0 ? 1 : (selfListSize / step + 1));
- for (int pos = 0; pos < selfListSize && pos > -1; pos += step) {
- if (!keepRemainder && pos > selfListSize - size) {
- break;
- }
- List<T> element = new ArrayList<>(size);
- for (int offs = pos; offs < pos + size && offs < selfListSize; offs++) {
- element.add(selfList.get(offs));
- }
- answer.add(element);
- }
- }
- return answer;
+ public static <T> List<T> toUnique(List<T> self) {
+ return toUnique(self, (Comparator<T>) null);
+ }
+
+ /**
+ * Returns a Collection containing the items from the Iterable but with duplicates removed.
+ * The items in the Iterable are compared by the given Closure condition.
+ * For each duplicate, the first member which is returned from the
+ * Iterable is retained, but all other ones are removed.
+ * <p>
+ * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
+ * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
+ * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
+ * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
+ * <p>
+ * <pre class="groovyTestCase">
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
+ *
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * def list2 = list.toUnique{ p1, p2 {@code ->} p1.lname != p2.lname ? p1.lname <=> p2.lname : p1.fname <=> p2.fname }
+ * assert( list2 == [a, b, c] {@code &&} list == [a, b, c, d] )
+ * def list3 = list.toUnique{ it.toString() }
+ * assert( list3 == [a, b, c] {@code &&} list == [a, b, c, d] )
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param condition a Closure used to determine unique items
+ * @return a new Collection
+ * @see #toUnique(Iterable, Comparator)
+ * @since 2.4.0
+ */
+ public static <T> Collection<T> toUnique(Iterable<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
+ Comparator<T> comparator = condition.getMaximumNumberOfParameters() == 1
+ ? new OrderBy<>(condition, true)
+ : new ClosureComparator<>(condition);
+ return toUnique(self, comparator);
}
/**
- * Iterates through this aggregate Object transforming each item into a new value using Closure.IDENTITY
- * as a transformer, basically returning a list of items copied from the original object.
- * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].iterator().collect()</pre>
+ * Returns a List containing the items from the List but with duplicates removed.
+ * The items in the List are compared by the given Closure condition.
+ * For each duplicate, the first member which is returned from the
+ * Iterable is retained, but all other ones are removed.
+ * <p>
+ * If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure
+ * should return a value used for comparison (either using {@link java.lang.Comparable#compareTo(java.lang.Object)} or
+ * {@link java.lang.Object#equals(java.lang.Object)}). If the closure takes two parameters, two items from the Iterable
+ * will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
+ * <p>
+ * <pre class="groovyTestCase">
+ * class Person {
+ * def fname, lname
+ * String toString() {
+ * return fname + " " + lname
+ * }
+ * }
*
- * @param self an aggregate Object with an Iterator returning its items
- * @return a Collection of the transformed values
- * @see Closure#IDENTITY
- * @since 1.8.5
+ * Person a = new Person(fname:"John", lname:"Taylor")
+ * Person b = new Person(fname:"Clark", lname:"Taylor")
+ * Person c = new Person(fname:"Tom", lname:"Cruz")
+ * Person d = new Person(fname:"Clark", lname:"Taylor")
+ *
+ * def list = [a, b, c, d]
+ * def list2 = list.toUnique{ p1, p2 {@code ->} p1.lname != p2.lname ? p1.lname <=> p2.lname : p1.fname <=> p2.fname }
+ * assert( list2 == [a, b, c] {@code &&} list == [a, b, c, d] )
+ * def list3 = list.toUnique{ it.toString() }
+ * assert( list3 == [a, b, c] {@code &&} list == [a, b, c, d] )
+ * </pre>
+ *
+ * @param self a List
+ * @param condition a Closure used to determine unique items
+ * @return a new List
+ * @see #toUnique(Iterable, Comparator)
+ * @since 2.4.0
*/
- @SuppressWarnings("unchecked")
- public static Collection collect(Object self) {
- return collect(self, Closure.IDENTITY);
+ public static <T> List<T> toUnique(List<T> self, @ClosureParams(value = FromString.class, options = {"T", "T,T"}) Closure condition) {
+ return (List<T>) toUnique((Iterable<T>) self, condition);
}
/**
- * Iterates through this aggregate Object transforming each item into a new value using the
- * <code>transform</code> closure, returning a list of transformed values.
- * Example:
- * <pre class="groovyTestCase">def list = [1, 'a', 1.23, true ]
- * def types = list.collect { it.class }
- * assert types == [Integer, String, BigDecimal, Boolean]</pre>
+ * Iterates through an aggregate type or data structure,
+ * passing each item to the given closure. Custom types may utilize this
+ * method by simply providing an "iterator()" method. The items returned
+ * from the resulting iterator will be passed to the closure.
+ * <pre class="groovyTestCase">
+ * String result = ''
+ * ['a', 'b', 'c'].each{ result += it }
+ * assert result == 'abc'
+ * </pre>
*
- * @param self an aggregate Object with an Iterator returning its items
- * @param transform the closure used to transform each item of the aggregate object
- * @return a List of the transformed values
+ * @param self the object over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self Object
* @since 1.0
*/
- public static <T> List<T> collect(Object self, Closure<T> transform) {
- return collect(self, new ArrayList<>(), transform);
+ public static <T> T each(T self, @ClosureParams(value=FromString.class, options="?") Closure closure) {
+ each(InvokerHelper.asIterator(self), closure);
+ return self;
}
/**
- * Iterates through this aggregate Object transforming each item into a new value using the <code>transform</code> closure
- * and adding it to the supplied <code>collector</code>.
+ * Iterates through an aggregate type or data structure,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
+ * <pre class="groovyTestCase">
+ * String result = ''
+ * ['a', 'b', 'c'].eachWithIndex{ letter, index {@code ->} result += "$index:$letter" }
+ * assert result == '0:a1:b2:c'
+ * </pre>
*
- * @param self an aggregate Object with an Iterator returning its items
- * @param collector the Collection to which the transformed values are added
- * @param transform the closure used to transform each item of the aggregate object
- * @return the collector with all transformed values added to it
+ * @param self an Object
+ * @param closure a Closure to operate on each item
+ * @return the self Object
* @since 1.0
*/
- public static <T, C extends Collection<T>> C collect(Object self, C collector, Closure<? extends T> transform) {
- return collect(InvokerHelper.asIterator(self), collector, transform);
+ public static <T> T eachWithIndex(T self, @ClosureParams(value=FromString.class, options="?,Integer") Closure closure) {
+ final Object[] args = new Object[2];
+ int counter = 0;
+ for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
+ args[0] = iter.next();
+ args[1] = counter++;
+ closure.call(args);
+ }
+ return self;
}
/**
- * Iterates through this Iterator transforming each item into a new value using the
- * <code>transform</code> closure, returning a list of transformed values.
+ * Iterates through an iterable type,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self an Iterator
- * @param transform the closure used to transform each item
- * @return a List of the transformed values
- * @since 2.5.0
+ * @param self an Iterable
+ * @param closure a Closure to operate on each item
+ * @return the self Iterable
+ * @since 2.3.0
*/
- public static <E, T> List<T> collect(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {
- return collect(self, new ArrayList<>(), transform);
+ public static <T> Iterable<T> eachWithIndex(Iterable<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ eachWithIndex(self.iterator(), closure);
+ return self;
}
/**
- * Iterates through this Iterator transforming each item into a new value using the <code>transform</code> closure
- * and adding it to the supplied <code>collector</code>.
+ * Iterates through an iterator type,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self an Iterator
- * @param collector the Collection to which the transformed values are added
- * @param transform the closure used to transform each item
- * @return the collector with all transformed values added to it
- * @since 2.5.0
+ * @param self an Iterator
+ * @param closure a Closure to operate on each item
+ * @return the self Iterator (now exhausted)
+ * @since 2.3.0
*/
- public static <E, T, C extends Collection<T>> C collect(Iterator<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {
+ public static <T> Iterator<T> eachWithIndex(Iterator<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ final Object[] args = new Object[2];
+ int counter = 0;
while (self.hasNext()) {
- collector.add(transform.call(self.next()));
+ args[0] = self.next();
+ args[1] = counter++;
+ closure.call(args);
}
- return collector;
+ return self;
}
/**
- * Iterates through this collection transforming each entry into a new value using Closure.IDENTITY
- * as a transformer, basically returning a list of items copied from the original collection.
- * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].collect()</pre>
+ * Iterates through a Collection,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self an Iterable
- * @return a List of the transformed values
- * @see Closure#IDENTITY
- * @since 2.5.0
+ * @param self a Collection
+ * @param closure a Closure to operate on each item
+ * @return the self Collection
+ * @since 2.4.0
*/
- @SuppressWarnings("unchecked")
- public static <T> List<T> collect(Iterable<T> self) {
- return collect(self, (Closure<T>) Closure.IDENTITY);
+ public static <T> Collection<T> eachWithIndex(Collection<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ return (Collection<T>) eachWithIndex((Iterable<T>) self, closure);
}
/**
- * Iterates through this Iterable transforming each entry into a new value using the <code>transform</code> closure
- * returning a list of transformed values.
- * <pre class="groovyTestCase">assert [2,4,6] == [1,2,3].collect { it * 2 }</pre>
+ * Iterates through a List,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self an Iterable
- * @param transform the closure used to transform each item of the collection
- * @return a List of the transformed values
- * @since 2.5.0
+ * @param self a List
+ * @param closure a Closure to operate on each item
+ * @return the self List
+ * @since 2.4.0
*/
- public static <E, T> List<T> collect(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {
- return collect(self.iterator(), transform);
+ public static <T> List<T> eachWithIndex(List<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ return (List<T>) eachWithIndex((Iterable<T>) self, closure);
}
/**
- * Iterates through this collection transforming each value into a new value using the <code>transform</code> closure
- * and adding it to the supplied <code>collector</code>.
- * <pre class="groovyTestCase">assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }</pre>
+ * Iterates through a Set,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self an Iterable
- * @param collector the Collection to which the transformed values are added
- * @param transform the closure used to transform each item
- * @return the collector with all transformed values added to it
- * @since 2.5.0
+ * @param self a Set
+ * @param closure a Closure to operate on each item
+ * @return the self Set
+ * @since 2.4.0
*/
- public static <E, T, C extends Collection<T>> C collect(Iterable<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {
- for (E element : self) {
- collector.add(transform.call(element));
- if (transform.getDirective() == Closure.DONE) {
- break;
- }
- }
- return collector;
+ public static <T> Set<T> eachWithIndex(Set<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ return (Set<T>) eachWithIndex((Iterable<T>) self, closure);
}
/**
- * Recursively iterates through this collection transforming each non-Collection value
- * into a new value using the closure as a transformer. Returns a potentially nested
- * list of transformed values.
- * <pre class="groovyTestCase">
- * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
- * </pre>
+ * Iterates through a SortedSet,
+ * passing each item and the item's index (a counter starting at
+ * zero) to the given closure.
*
- * @param self a collection
- * @param transform the closure used to transform each item of the collection
- * @return the resultant collection
- * @since 1.8.1
+ * @param self a SortedSet
+ * @param closure a Closure to operate on each item
+ * @return the self SortedSet
+ * @since 2.4.0
*/
- public static List collectNested(Collection self, Closure transform) {
- return collectNested(self, new ArrayList(self.size()), transform);
+ public static <T> SortedSet<T> eachWithIndex(SortedSet<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) {
+ return (SortedSet<T>) eachWithIndex((Iterable<T>) self, closure);
}
/**
- * Recursively iterates through this Iterable transforming each non-Collection value
- * into a new value using the closure as a transformer. Returns a potentially nested
- * list of transformed values.
- * <pre class="groovyTestCase">
- * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
- * </pre>
+ * Iterates through an Iterable, passing each item to the given closure.
*
- * @param self an Iterable
- * @param transform the closure used to transform each item of the Iterable
- * @return the resultant list
- * @since 2.2.0
- */
- public static List collectNested(Iterable self, Closure transform) {
- return collectNested(self, new ArrayList(), transform);
+ * @param self the Iterable over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self Iterable
+ */
+ public static <T> Iterable<T> each(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ each(self.iterator(), closure);
+ return self;
}
/**
- * Recursively iterates through this Iterable transforming each non-Collection value
- * into a new value using the <code>transform</code> closure. Returns a potentially nested
- * collection of transformed values.
- * <pre class="groovyTestCase">
- * def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 }
- * assert x == [2,[4,6],[8],[]]
- * assert x instanceof Vector
- * </pre>
+ * Iterates through an Iterator, passing each item to the given closure.
*
- * @param self an Iterable
- * @param collector an initial Collection to which the transformed values are added
- * @param transform the closure used to transform each element of the Iterable
- * @return the collector with all transformed values added to it
- * @since 2.2.0
+ * @param self the Iterator over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self Iterator
+ * @since 2.4.0
*/
- @SuppressWarnings("unchecked")
- public static <C extends Collection> C collectNested(Iterable self, C collector, Closure transform) {
- for (Object element : self) {
- if (element instanceof Collection) {
- Collection c = (Collection) element;
- collector.add(collectNested(c, createSimilarCollection(collector, c.size()), transform));
- } else {
- collector.add(transform.call(element));
- }
- if (transform.getDirective() == Closure.DONE) {
- break;
- }
+ public static <T> Iterator<T> each(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ while (self.hasNext()) {
+ Object arg = self.next();
+ closure.call(arg);
}
- return collector;
+ return self;
}
/**
- * Projects each item from a source Iterable to a collection and concatenates (flattens) the resulting collections into a single list.
- * <p>
- * <pre class="groovyTestCase">
- * def nums = 1..10
- * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
- * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
- *
- * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
- * def smallAnimals = animals.collectMany{ it.size() {@code >} 3 ? [] : [it.toLowerCase()] }
- * assert smallAnimals == ['cat', 'dog']
- *
- * def orig = nums as Set
- * def origPlusIncrements = orig.collectMany{ [it, it+1] }
- * assert origPlusIncrements.size() == orig.size() * 2
- * assert origPlusIncrements.unique().size() == orig.size() + 1
- * </pre>
+ * Iterates through a Collection, passing each item to the given closure.
*
- * @param self an Iterable
- * @param projection a projecting Closure returning a collection of items
- * @return a list created from the projected collections concatenated (flattened) together
- * @see #sum(java.lang.Iterable, groovy.lang.Closure)
- * @since 2.2.0
+ * @param self the Collection over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self Collection
+ * @since 2.4.0
*/
- public static <T, E> List<T> collectMany(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
- return collectMany(self, new ArrayList<>(), projection);
+ public static <T> Collection<T> each(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (Collection<T>) each((Iterable<T>) self, closure);
}
/**
- * Projects each item from a source collection to a result collection and concatenates (flattens) the resulting
- * collections adding them into the <code>collector</code>.
- * <p>
- * <pre class="groovyTestCase">
- * def animals = ['CAT', 'DOG', 'ELEPHANT']
- * def smallAnimals = animals.collectMany(['ant', 'bee']){ it.size() > 3 ? [] : [it.toLowerCase()] }
- * assert smallAnimals == ['ant', 'bee', 'cat', 'dog']
- *
- * def nums = 1..5
- * def origPlusIncrements = nums.collectMany([] as Set){ [it, it+1] }
- * assert origPlusIncrements.size() == nums.size() + 1
- *
- * @groovy.transform.TypeChecked void test() {
- * LinkedHashSet<String> lhs = ['abc','def'].collectMany(new LinkedHashSet<>()){ it.iterator().collect() }
- * assert lhs == ['a','b','c','d','e','f'] as Set<String>
- * }
- * test()
- * </pre>
+ * Iterates through a List, passing each item to the given closure.
*
- * @param self an Iterable
- * @param collector an initial collection to add the projected items to
- * @param projection a projecting Closure returning a collection of items
- * @return the collector with the projected collections concatenated (flattened) into it
- * @since 2.2.0
+ * @param self the List over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self List
+ * @since 2.4.0
*/
- public static <T, E, C extends Collection<T>> C collectMany(Iterable<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
- return collectMany(self.iterator(), collector, projection);
+ public static <T> List<T> each(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (List<T>) each((Iterable<T>) self, closure);
}
/**
- * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
- * collections adding them into the <code>collector</code>.
- * <p>
- * <pre class="groovyTestCase">
- * def map = [bread:3, milk:5, butter:2]
- * def result = map.collectMany(['x']){ k, v {@code ->} if (k.startsWith('b')) k.toList() }
- * assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
- * </pre>
+ * Iterates through a Set, passing each item to the given closure.
*
- * @param self a map
- * @param collector an initial collection to add the projected items to
- * @param projection a projecting Closure returning a collection of items
- * @return the collector with the projected collections concatenated (flattened) to it
- * @since 1.8.8
+ * @param self the Set over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self Set
+ * @since 2.4.0
*/
- public static <T, K, V, C extends Collection<T>> C collectMany(Map<K, V> self, C collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends Collection<? extends T>> projection) {
- for (Map.Entry<K, V> entry : self.entrySet()) {
- var items = callClosureForMapEntry(projection, entry);
- if (items != null && !items.isEmpty()) collector.addAll(items);
- }
- return collector;
+ public static <T> Set<T> each(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (Set<T>) each((Iterable<T>) self, closure);
}
/**
- * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
- * collections adding them into a collection.
- * <p>
- * <pre class="groovyTestCase">
- * def map = [bread:3, milk:5, butter:2]
- * def result = map.collectMany{ k, v {@code ->} k.startsWith('b') ? k.toList() : [] }
- * assert result == ['b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
- * </pre>
+ * Iterates through a SortedSet, passing each item to the given closure.
*
- * @param self a map
- * @param projection a projecting Closure returning a collection of items
- * @return a list created from the projected collections concatenated (flattened) together
- * @since 1.8.8
+ * @param self the SortedSet over which we iterate
+ * @param closure the closure applied on each element found
+ * @return the self SortedSet
+ * @since 2.4.0
*/
- public static <T, K, V> List<T> collectMany(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends Collection<? extends T>> projection) {
- return collectMany(self, new ArrayList<>(), projection);
+ public static <T> SortedSet<T> each(SortedSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (SortedSet<T>) each((Iterable<T>) self, closure);
}
/**
- * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
- * <p>
- * <pre class="groovyTestCase">
- * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
- * def squaresAndCubesOfEvens = numsIter.collectMany{ if (it % 2 == 0) [it**2, it**3] }
- * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
- * </pre>
- * <p>
- * <pre class="groovyTestCase">
- * var letters = 'a'..'z'
- * var pairs = letters.collectMany{ a ->
- * letters.collectMany{ b ->
- * if (a != b) ["$a$b"]
- * }
- * }
- * assert pairs.join(',').matches('ab,ac,ad,.*,zw,zx,zy')
- * </pre>
+ * Allows a Map to be iterated through using a closure. If the
+ * closure takes one parameter then it will be passed the Map.Entry
+ * otherwise if the closure takes two parameters then it will be
+ * passed the key and the value.
+ * <pre class="groovyTestCase">def result = ""
+ * [a:1, b:3].each { key, value {@code ->} result += "$key$value" }
+ * assert result == "a1b3"</pre>
+ * <pre class="groovyTestCase">def result = ""
+ * [a:1, b:3].each { entry {@code ->} result += entry }
+ * assert result == "a=1b=3"</pre>
*
- * @param self an iterator
- * @param collector an initial collection to add the projected items to
- * @param projection a projecting Closure returning a collection of items
- * @return the collector with the projected collections concatenated (flattened) to it
- * @see #sum(Iterator, groovy.lang.Closure)
- * @since 1.8.1
+ * In general, the order in which the map contents are processed
+ * cannot be guaranteed. In practise, specialized forms of Map,
+ * e.g. a TreeMap will have its contents processed according to
+ * the natural ordering of the map.
+ *
+ * @param self the map over which we iterate
+ * @param closure the 1 or 2 arg closure applied on each entry of the map
+ * @return returns the self parameter
+ * @since 1.5.0
*/
- public static <T, E, C extends Collection<T>> C collectMany(Iterator<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
- while (self.hasNext()) {
- E element = self.next();
- var items = projection.call(element);
- if (items != null) collector.addAll(items);
+ public static <K, V> Map<K, V> each(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ callClosureForMapEntry(closure, entry);
}
- return collector;
+ return self;
}
/**
- * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
- * <p>
- * <pre class="groovyTestCase">
- * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
- * def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
- * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
- * </pre>
+ * Allows a Map to be iterated through in reverse order using a closure.
*
- * @param self an iterator
- * @param projection a projecting Closure returning a collection of items
- * @return a list created from the projected collections concatenated (flattened) together
- * @see #collectMany(Iterator, Collection, groovy.lang.Closure)
- * @since 1.8.1
+ * In general, the order in which the map contents are processed
+ * cannot be guaranteed. In practise, specialized forms of Map,
+ * e.g. a TreeMap will have its contents processed according to the
+ * reverse of the natural ordering of the map.
+ *
+ * @param self the map over which we iterate
+ * @param closure the 1 or 2 arg closure applied on each entry of the map
+ * @return returns the self parameter
+ * @see #each(Map, Closure)
+ * @since 1.7.2
*/
- public static <T, E> List<T> collectMany(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
- return collectMany(self, new ArrayList<>(), projection);
+ @SuppressWarnings("unchecked")
+ public static <K, V> Map<K, V> reverseEach(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
+ final Iterator<Map.Entry<K, V>> entries = reverse(self.entrySet().iterator());
+ while (entries.hasNext()) {
+ callClosureForMapEntry(closure, entries.next());
+ }
+ return self;
}
/**
- * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
- * returning the <code>collector</code> with all transformed values added to it.
- * <pre class="groovyTestCase">assert [a:1, b:2].collect( [] as HashSet ) { key, value {@code ->} key*value } == ["a", "bb"] as Set
- * assert [3:20, 2:30].collect( [] as HashSet ) { entry {@code ->} entry.key * entry.value } == [60] as Set</pre>
+ * Allows a Map to be iterated through using a closure. If the
+ * closure takes two parameters then it will be passed the Map.Entry and
+ * the item's index (a counter starting at zero) otherwise if the closure
+ * takes three parameters then it will be passed the key, the value, and
+ * the index.
+ * <pre class="groovyTestCase">def result = ""
+ * [a:1, b:3].eachWithIndex { key, value, index {@code ->} result += "$index($key$value)" }
+ * assert result == "0(a1)1(b3)"</pre>
+ * <pre class="groovyTestCase">def result = ""
+ * [a:1, b:3].eachWithIndex { entry, index {@code ->} result += "$index($entry)" }
+ * assert result == "0(a=1)1(b=3)"</pre>
*
- * @param self a Map
- * @param collector the Collection to which transformed values are added
- * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
- * @return the collector with all transformed values added to it
- * @since 1.0
+ * @param self the map over which we iterate
+ * @param closure a 2 or 3 arg Closure to operate on each item
+ * @return the self Object
+ * @since 1.5.0
*/
- public static <T, K, V, C extends Collection<T>> C collect(Map<K, V> self, C collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends T> transform) {
+ public static <K, V> Map<K, V> eachWithIndex(Map<K, V> self, @ClosureParams(value=MapEntryOrKeyValue.class, options="index=true") Closure<?> closure) {
+ int counter = 0;
for (Map.Entry<K, V> entry : self.entrySet()) {
- collector.add(callClosureForMapEntry(transform, entry));
+ callClosureForMapEntryAndCounter(closure, entry, counter++);
}
- return collector;
+ return self;
}
/**
- * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
- * returning a list of transformed values.
- * <pre class="groovyTestCase">assert [a:1, b:2].collect { key, value {@code ->} key*value } == ["a", "bb"]
- * assert [3:20, 2:30].collect { entry {@code ->} entry.key * entry.value } == [60, 60]</pre>
+ * Iterate over each element of the list in the reverse order.
+ * <pre class="groovyTestCase">def result = []
+ * [1,2,3].reverseEach { result << it }
+ * assert result == [3,2,1]</pre>
*
- * @param self a Map
- * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
- * @return the resultant list of transformed values
- * @since 1.0
+ * @param self a List
+ * @param closure a closure to which each item is passed.
+ * @return the original list
+ * @since 1.5.0
*/
- public static <T, K, V> List<T> collect(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> transform) {
- return collect(self, new ArrayList<>(self.size()), transform);
+ public static <T> List<T> reverseEach(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ each(new ReverseListIterator<>(self), closure);
+ return self;
}
/**
- * Iterates through this Map transforming each map entry using the <code>transform</code> closure
- * returning a map of the transformed entries.
+ * Iterate over each element of the set in reverse order.
* <pre class="groovyTestCase">
- * assert [a:1, b:2].collectEntries( [:] ) { k, v {@code ->} [v, k] } == [1:'a', 2:'b']
- * assert [a:1, b:2].collectEntries( [30:'C'] ) { key, value {@code ->}
- * [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
+ * TreeSet navSet = [2, 4, 1, 3] // natural order is sorted
+ * List result = []
+ * navSet.reverseEach { result << it }
+ * assert result == [4, 3, 2, 1]
* </pre>
- * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
- * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
- * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
- * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
*
- * @param self a Map
- * @param collector the Map into which the transformed entries are put
- * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return the collector with all transformed values added to it
- * @see #collect(Map, Collection, Closure)
- * @since 1.7.9
+ * @param self a NavigableSet
+ * @param closure a closure to which each item is passed.
+ * @return the original NavigableSet
+ * @since 4.0.11
*/
- public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Map<K, V> collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
- for (Map.Entry<X, Y> entry : self.entrySet()) {
- addEntry(collector, callClosureForMapEntry(transform, entry));
- }
- return collector;
+ public static <T> NavigableSet<T> reverseEach(NavigableSet<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ each(self.descendingIterator(), closure);
+ return self;
}
/**
- * Iterates through this Map transforming each entry using the <code>transform</code> closure
- * and returning a map of the transformed entries.
- * <pre class="groovyTestCase">
- * assert [a:1, b:2].collectEntries { key, value {@code ->} [value, key] } == [1:'a', 2:'b']
- * assert [a:1, b:2].collectEntries { key, value {@code ->}
- * [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
+ * Used to determine if the given predicate closure is valid (i.e. returns
+ * <code>true</code> for all items in this data structure).
+ * A simple example for a list:
+ * <pre>def list = [3,4,5]
+ * def greaterThanTwo = list.every { it {@code >} 2 }
* </pre>
- * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
- * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
- * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
- * If your Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
*
- * @param self a Map
- * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return a Map of the transformed entries
- * @see #collect(Map, Collection, Closure)
- * @since 1.7.9
+ * @param self the object over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if every iteration of the object matches the closure predicate
+ * @since 1.0
*/
- @SuppressWarnings("unchecked")
- public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
- return collectEntries(self, (Map) createSimilarMap(self), transform);
+ public static boolean every(Object self, Closure predicate) {
+ return every(InvokerHelper.asIterator(self), predicate);
}
/**
- * A variant of collectEntries for Iterators.
+ * Used to determine if the given predicate closure is valid (i.e. returns
+ * <code>true</code> for all items in this iterator).
+ * A simple example for a list:
+ * <pre>def list = [3,4,5]
+ * def greaterThanTwo = list.iterator().every { it {@code >} 2 }
+ * </pre>
*
- * @param self an Iterator
- * @param transform the closure used for transforming, which has an item from self as the parameter and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return a Map of the transformed entries
- * @see #collectEntries(Iterable, Closure)
- * @since 1.8.7
+ * @param self the iterator over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if every iteration of the object matches the closure predicate
+ * @since 2.3.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
- return collectEntries(self, new LinkedHashMap<>(), transform);
+ public static <T> boolean every(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
+ while (self.hasNext()) {
+ if (!bcw.call(self.next())) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * Iterates through this Iterable transforming each item using the <code>transform</code> closure
- * and returning a map of the resulting transformed entries.
- * <pre class="groovyTestCase">
- * def letters = "abc"
- * // collect letters with index using list style
- * assert (0..2).collectEntries { index {@code ->} [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
- * // collect letters with index using map style
- * assert (0..2).collectEntries { index {@code ->} [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
+ * Used to determine if the given predicate closure is valid (i.e. returns
+ * <code>true</code> for all items in this iterable).
+ * A simple example for a list:
+ * <pre>def list = [3,4,5]
+ * def greaterThanTwo = list.every { it {@code >} 2 }
* </pre>
- * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
- * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
- * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
*
- * @param self an Iterable
- * @param transform the closure used for transforming, which has an item from self as the parameter and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return a Map of the transformed entries
- * @see #collectEntries(Iterator, Closure)
- * @since 1.8.7
+ * @param self the iterable over which we iterate
+ * @param predicate the closure predicate used for matching
+ * @return true if every iteration of the object matches the closure predicate
+ * @since 2.3.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
- return collectEntries(self.iterator(), transform);
+ public static <T> boolean every(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure predicate) {
+ return every(self.iterator(), predicate);
}
/**
- * A variant of collectEntries for Iterators using the identity closure as the transform.
+ * Iterates over the entries of a map, and checks whether a predicate is
+ * valid for all entries. If the
+ * closure takes one parameter then it will be passed the Map.Entry
+ * otherwise if the closure takes two parameters then it will be
+ * passed the key and the value.
+ * <pre class="groovyTestCase">def map = [a:1, b:2.0, c:2L]
+ * assert !map.every { key, value {@code ->} value instanceof Integer }
+ * assert map.every { entry {@code ->} entry.value instanceof Number }</pre>
*
- * @param self an Iterator
- * @return a Map of the transformed entries
- * @see #collectEntries(Iterable)
- * @since 1.8.7
+ * @param self the map over which we iterate
+ * @param predicate the 1 or 2 arg Closure predicate used for matching
+ * @return true if every entry of the map matches the closure predicate
+ * @since 1.5.0
*/
- public static <K, V> Map<K, V> collectEntries(Iterator<?> self) {
- return collectEntries(self, Closure.IDENTITY);
+ public static <K, V> boolean every(Map<K, V> self, @ClosureParams(value = MapEntryOrKeyValue.class) Closure predicate) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (!bcw.callForMap(entry)) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * A variant of collectEntries for Iterable objects using the identity closure as the transform.
- * The source Iterable should contain a list of <code>[key, value]</code> tuples or <code>Map.Entry</code> objects.
+ * Iterates over every element of a collection, and checks whether all
+ * elements are <code>true</code> according to the Groovy Truth.
+ * Equivalent to <code>self.every({element {@code ->} element})</code>
* <pre class="groovyTestCase">
- * def nums = [1, 10, 100, 1000]
- * def tuples = nums.collect{ [it, it.toString().size()] }
- * assert tuples == [[1, 1], [10, 2], [100, 3], [1000, 4]]
- * def map = tuples.collectEntries()
- * assert map == [1:1, 10:2, 100:3, 1000:4]
+ * assert [true, true].every()
+ * assert [1, 1].every()
+ * assert ![1, 0].every()
* </pre>
*
- * @param self an Iterable
- * @return a Map of the transformed entries
- * @see #collectEntries(Iterator)
- * @since 1.8.7
+ * @param self the object over which we iterate
+ * @return true if every item in the collection matches satisfies Groovy truth
+ * @since 1.5.0
*/
- public static <K, V> Map<K, V> collectEntries(Iterable<?> self) {
- return collectEntries(self.iterator());
+ public static boolean every(Object self) {
+ BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker();
+ for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
+ if (!bmi.convertToBoolean(iter.next())) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * A variant of collectEntries for Iterators using a supplied map as the destination of transformed entries.
+ * Iterates over the collection of items which this Object represents and returns each item that matches
+ * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
+ * method used by switch statements. This method can be used with different
+ * kinds of filters like regular expressions, classes, ranges etc.
+ * Example:
+ * <pre class="groovyTestCase">
+ * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
+ * assert list.grep( ~/a+/ ) == ['a', 'aa']
+ * assert list.grep( ~/../ ) == ['aa', 'bc']
+ * assert list.grep( Number ) == [ 3, 4.5 ]
+ * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
+ * </pre>
*
- * @param self an Iterator
- * @param collector the Map into which the transformed entries are put
- * @param transform the closure used for transforming, which has an item from self as the parameter and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return the collector with all transformed values added to it
- * @since 1.8.7
+ * @param self the object over which we iterate
+ * @param filter the filter to perform on the object (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
+ * @return a collection of objects which match the filter
+ * @since 1.5.6
+ */
+ @SuppressWarnings("unchecked")
+ public static Collection grep(Object self, Object filter) {
+ Collection answer = createSimilarOrDefaultCollection(self);
+ BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
+ for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
+ Object object = iter.next();
+ if (bmi.invoke(filter, object)) {
+ answer.add(object);
+ }
+ }
+ return answer;
+ }
+
+ /**
+ * Iterates over the collection of items and returns each item that matches
+ * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
+ * method used by switch statements. method can be used with different
+ * kinds of filters like regular expressions, classes, ranges etc.
+ * Example:
+ * <pre class="groovyTestCase">
+ * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
+ * assert list.grep( ~/a+/ ) == ['a', 'aa']
+ * assert list.grep( ~/../ ) == ['aa', 'bc']
+ * assert list.grep( Number ) == [ 3, 4.5 ]
+ * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
+ * </pre>
+ *
+ * @param self a collection
+ * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
+ * @return a collection of objects which match the filter
+ * @since 2.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
- while (self.hasNext()) {
- E element = self.next();
- addEntry(collector, transform.call(element));
+ public static <T> Collection<T> grep(Collection<T> self, Object filter) {
+ Collection<T> answer = createSimilarCollection(self);
+ BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
+ for (T element : self) {
+ if (bmi.invoke(filter, element)) {
+ answer.add(element);
+ }
}
- return collector;
+ return answer;
}
/**
- * A variant of collectEntries for Iterators with separate functions for transforming the keys and values.
- * The supplied collector map is used as the destination for transformed entries.
+ * Iterates over the collection of items and returns each item that matches
+ * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
+ * method used by switch statements. This method can be used with different
+ * kinds of filters like regular expressions, classes, ranges etc.
+ * Example:
+ * <pre class="groovyTestCase">
+ * def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
+ * assert list.grep( ~/a+/ ) == ['a', 'aa']
+ * assert list.grep( ~/../ ) == ['aa', 'bc']
+ * assert list.grep( Number ) == [ 3, 4.5 ]
+ * assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
+ * </pre>
*
- * @param self an Iterator
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Iterator elements into keys
- * @param valueTransform a function for transforming Iterator elements into values
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self a List
+ * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
+ * @return a List of objects which match the filter
+ * @since 2.4.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
- while (self.hasNext()) {
- E element = self.next();
- addEntry(collector, Tuple2.tuple(keyTransform.apply(element), valueTransform.apply(element)));
- }
- return collector;
+ public static <T> List<T> grep(List<T> self, Object filter) {
+ return (List<T>) grep((Collection<T>) self, filter);
}
/**
- * A variant of collectEntries for Iterators with separate functions for transforming the keys and values.
+ * Iterates over the collection of items and returns each item that matches
+ * the given filter - calling the <code>{@link #isCase(java.lang.Object, java.lang.Object)}</code>
+ * method used by switch statements. This method can be used with different
+ * kinds of filters like regular expressions, classes, ranges etc.
+ * Example:
+ * <pre class="groovyTestCase">
+ * def set = ['a', 'b', 'aa', 'bc', 3, 4.5] as Set
+ * assert set.grep( ~/a+/ ) == ['a', 'aa'] as Set
+ * assert set.grep( ~/../ ) == ['aa', 'bc'] as Set
+ * assert set.grep( Number ) == [ 3, 4.5 ] as Set
+ * assert set.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ] as Set
+ * </pre>
*
- * @param self an Iterator
- * @param keyTransform a function for transforming Iterator elements into keys
- * @param valueTransform a function for transforming Iterator elements into values
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self a Set
+ * @param filter the filter to perform on each element of the collection (using the {@link #isCase(java.lang.Object, java.lang.Object)} method)
+ * @return a Set of objects which match the filter
+ * @since 2.4.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
- return collectEntries(self, new LinkedHashMap<>(), keyTransform, valueTransform);
+ public static <T> Set<T> grep(Set<T> self, Object filter) {
+ return (Set<T>) grep((Collection<T>) self, filter);
}
/**
- * A variant of collectEntries for Iterables with separate functions for transforming the keys and values.
- * The supplied collector map is used as the destination for transformed entries.
+ * Iterates over the collection of items which this Object represents and returns each item that matches
+ * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * <p>
+ * Example:
* <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * assert languages.collectEntries([clojure:7], String::toLowerCase, String::size) ==
- * [clojure:7, groovy:6, java:4, kotlin:6, scala:5]
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
* </pre>
*
- * @param self an Iterable
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Iterable elements into keys
- * @param valueTransform a function for transforming Iterable elements into values
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self the object over which we iterate
+ * @return a collection of objects which match the filter
+ * @since 1.8.1
+ * @see Closure#IDENTITY
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Map<K, V> collector, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
- return collectEntries(self.iterator(), collector, keyTransform, valueTransform);
+ public static Collection grep(Object self) {
+ return grep(self, Closure.IDENTITY);
}
/**
- * A variant of collectEntries for Iterables with separate functions for transforming the keys and values.
+ * Iterates over the collection returning each element that matches
+ * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * <p>
+ * Example:
* <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * assert languages.collectEntries(String::toLowerCase, String::size) ==
- * [groovy:6, java:4, kotlin:6, scala:5]
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
* </pre>
*
- * @param self an Iterable
- * @param keyTransform a function for transforming Iterable elements into keys
- * @param valueTransform a function for transforming Iterable elements into values
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self a Collection
+ * @return a collection of elements satisfy Groovy truth
+ * @see Closure#IDENTITY
+ * @since 2.0
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
- return collectEntries(self.iterator(), new LinkedHashMap<>(), keyTransform, valueTransform);
+ public static <T> Collection<T> grep(Collection<T> self) {
+ return grep(self, Closure.IDENTITY);
}
/**
- * A variant of collectEntries for Maps with separate functions for transforming the keys and values.
- * The supplied collector map is used as the destination for transformed entries.
+ * Iterates over the collection returning each element that matches
+ * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * <p>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.grep() == [1, 2, true, 'foo', [4, 5]]
+ * </pre>
*
- * @param self a Map
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Map keys
- * @param valueTransform a function for transforming Map values
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self a List
+ * @return a List of elements satisfy Groovy truth
+ * @see Closure#IDENTITY
+ * @since 2.4.0
*/
- public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Map<K, V> collector, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform) {
- for (Map.Entry<X, Y> entry : self.entrySet()) {
- addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), valueTransform.apply(entry.getValue())));
- }
- return collector;
+ public static <T> List<T> grep(List<T> self) {
+ return grep(self, Closure.IDENTITY);
}
/**
- * A variant of collectEntries for Maps with separate functions for transforming the keys and values.
+ * Iterates over the collection returning each element that matches
+ * using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
+ * <p>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
+ * assert items.grep() == [1, 2, true, 'foo', [4, 5]] as Set
+ * </pre>
*
- * @param self a Map
- * @param keyTransform a function for transforming Map keys
- * @param valueTransform a function for transforming Map values
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self a Set
+ * @return a Set of elements satisfy Groovy truth
+ * @see Closure#IDENTITY
+ * @since 2.4.0
*/
- public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform) {
- return collectEntries(self, new LinkedHashMap<>(), keyTransform, valueTransform);
+ public static <T> Set<T> grep(Set<T> self) {
+ return grep(self, Closure.IDENTITY);
}
/**
- * A variant of withCollectedValues for Iterators.
+ * Counts the number of occurrences of the given value from the
+ * items within this Iterator.
+ * Comparison is done using Groovy's == operator (using
+ * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
+ * The iterator will become exhausted of elements after determining the count value.
*
- * @param keys an Iterator
- * @param collector the Map into which the transformed entries are put
- * @param valueTransform a function for transforming Iterator elements into values
- * @return the collector with all transformed values added to it
- * @see #withCollectedValues(Iterable, Map, Function)
- * @since 5.0.0
+ * @param self the Iterator from which we count the number of matching occurrences
+ * @param value the value being searched for
+ * @return the number of occurrences
+ * @since 1.5.0
*/
- public static <K, V> Map<K, V> withCollectedValues(Iterator<K> keys, Map<K, V> collector, Function<? super K, V> valueTransform) {
- return collectEntries(keys, collector, Function.identity(), valueTransform);
+ public static Number count(Iterator self, Object value) {
+ Objects.requireNonNull(self);
+ long answer = 0;
+ while (self.hasNext()) {
+ if (DefaultTypeTransformation.compareEqual(self.next(), value)) {
+ ++answer;
+ }
+ }
+ // for b/c with Java return an int if we can
+ if (answer <= Integer.MAX_VALUE) return (int) answer;
+ return answer;
}
/**
- * A variant of withCollectedValues for Iterators.
+ * Counts the number of occurrences which satisfy the given closure from the
+ * items within this Iterator.
+ * The iterator will become exhausted of elements after determining the count value.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2</pre>
*
- * @param keys an Iterator
- * @param valueTransform a function for transforming Iterator elements into values
- * @return a Map of the transformed entries
- * @see #withCollectedValues(Iterable, Function)
- * @since 5.0.0
+ * @param self the Iterator from which we count the number of matching occurrences
+ * @param closure a closure condition
+ * @return the number of occurrences
+ * @since 1.8.0
*/
- public static <K, V> Map<K, V> withCollectedValues(Iterator<K> keys, Function<? super K, V> valueTransform) {
- return withCollectedValues(keys, new LinkedHashMap<>(), valueTransform);
+ public static <T> Number count(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ long answer = 0;
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
+ while (self.hasNext()) {
+ if (bcw.call(self.next())) {
+ ++answer;
+ }
+ }
+ // for b/c with Java return an int if we can
+ if (answer <= Integer.MAX_VALUE) return (int) answer;
+ return answer;
}
/**
- * Transform Iterable elements into Map entries with keys unchanged
- * and values transformed using the supplied function.
- * The supplied collector map is used as the destination for transformed entries.
- * <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * assert languages.withCollectedValues([Clojure:7], String::size) ==
- * [Clojure:7, Groovy:6, Java:4, Kotlin:6, Scala:5]
- * </pre>
- * This method is a convenience method for {@link #collectEntries(Iterable, Map, Function, Function)}
- * with the {@code keyTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
+ * Counts the number of occurrences of the given value inside this Iterable.
+ * Comparison is done using Groovy's == operator (using
+ * <code>compareTo(value) == 0</code> or <code>equals(value)</code> ).
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count(4) == 2</pre>
*
- * @param keys an Iterable
- * @param collector the Map into which the transformed entries are put
- * @param valueTransform a function for transforming Iterable elements into values
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self the Iterable within which we count the number of occurrences
+ * @param value the value being searched for
+ * @return the number of occurrences
+ * @since 2.2.0
*/
- public static <K, V> Map<K, V> withCollectedValues(Iterable<K> keys, Map<K, V> collector, Function<? super K, V> valueTransform) {
- return collectEntries(keys.iterator(), collector, Function.identity(), valueTransform);
+ public static Number count(Iterable self, Object value) {
+ return count(self.iterator(), value);
}
/**
- * Transform Iterable elements into Map entries with keys unchanged
- * and values transformed using the supplied function.
- * <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * assert languages.withCollectedValues(String::size) ==
- * [Groovy:6, Java:4, Kotlin:6, Scala:5]
- * </pre>
- * This method is a convenience method for {@link #collectEntries(Iterable, Function, Function)}
- * with the {@code keyTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
+ * Counts the number of occurrences which satisfy the given closure from inside this Iterable.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5</pre>
*
- * @param keys an Iterable
- * @param valueTransform a function for transforming Iterable elements into values
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self the Iterable within which we count the number of occurrences
+ * @param closure a closure condition
+ * @return the number of occurrences
+ * @since 2.2.0
*/
- public static <K, V> Map<K, V> withCollectedValues(Iterable<K> keys, Function<? super K, V> valueTransform) {
- return withCollectedValues(keys.iterator(), new LinkedHashMap<>(), valueTransform);
+ public static <T> Number count(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return count(self.iterator(), closure);
}
/**
- * Transform a Maps' values leaving the keys unchanged.
- * Similar to {@link #withCollectedValues(Iterable, Map, Function)} but for Maps.
- * <pre class="groovyTestCase">
- * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
- * def squared = e {@code ->} e ** 2
- * assert lengths.collectValues([Clojure:49], squared) ==
- * [Clojure:49, Groovy:36, Java:16, Kotlin:36, Scala:25]
- * </pre>
+ * Counts the number of occurrences which satisfy the given closure from inside this map.
+ * If the closure takes one parameter then it will be passed the Map.Entry.
+ * Otherwise, the closure should take two parameters and will be passed the key and value.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">assert [a:1, b:1, c:2, d:2].count{ k,v {@code ->} k == 'a' {@code ||} v == 2 } == 3</pre>
*
- * @param keys a Map
- * @param collector the Map into which the transformed entries are put
- * @param valueTransform a function for transforming Map values
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self the map within which we count the number of occurrences
+ * @param closure a 1 or 2 arg Closure condition applying on the entries
+ * @return the number of occurrences
+ * @since 1.8.0
*/
- public static <K, V> Map<K, V> collectValues(Map<K, V> keys, Map<K, V> collector, Function<? super V, V> valueTransform) {
- for (Map.Entry<K, V> entry : keys.entrySet()) {
- addEntry(collector, Tuple2.tuple(entry.getKey(), valueTransform.apply(entry.getValue())));
+ public static <K,V> Number count(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
+ long answer = 0;
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (bcw.callForMap(entry)) {
+ ++answer;
+ }
}
- return collector;
+ // for b/c with Java return an int if we can
+ if (answer <= Integer.MAX_VALUE) return (int) answer;
+ return answer;
}
/**
- * Transform a Maps' values leaving the keys unchanged.
- * Similar to {@link #withCollectedValues(Iterable, Function)} but for Maps.
- * <pre class="groovyTestCase">
- * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
- * def squared = e {@code ->} e ** 2
- * assert lengths.collectValues(squared) == [Groovy:36, Java:16, Kotlin:36, Scala:25]
- * </pre>
+ * Convert an iterator to a List. The iterator will become
+ * exhausted of elements after making this conversion.
*
- * @param keys a Map
- * @param valueTransform a function for transforming Map values
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self an iterator
+ * @return a List
+ * @since 1.5.0
*/
- public static <K, V> Map<K, V> collectValues(Map<K, V> keys, Function<? super V, V> valueTransform) {
- return collectValues(keys, new LinkedHashMap<>(), valueTransform);
+ public static <T> List<T> toList(Iterator<T> self) {
+
+ List<T> answer = new ArrayList<>();
+ while (self.hasNext()) {
+ answer.add(self.next());
+ }
+ return answer;
}
/**
- * A variant of withCollectedKeys for Iterators.
+ * Convert an Iterable to a List. The Iterable's iterator will
+ * become exhausted of elements after making this conversion.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">def x = [1,2,3] as HashSet
+ * assert x.class == HashSet
+ * assert x.toList() instanceof List</pre>
*
- * @param values an Iterator
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Iterator elements into values
- * @return the collector with all transformed values added to it
- * @see #withCollectedKeys(Iterable, Map, Function)
- * @since 5.0.0
+ * @param self an Iterable
+ * @return a List
+ * @since 1.8.7
*/
- public static <K, V> Map<K, V> withCollectedKeys(Iterator<V> values, Map<K, V> collector, Function<? super V, K> keyTransform) {
- return collectEntries(values, collector, keyTransform, Function.identity());
+ public static <T> List<T> toList(Iterable<T> self) {
+ return toList(self.iterator());
}
/**
- * A variant of withCollectedKeys for Iterators.
+ * Convert an enumeration to a List.
*
- * @param values an Iterator
- * @param keyTransform a function for transforming Iterator elements into values
- * @return a Map of the transformed entries
- * @see #withCollectedKeys(Iterable, Function)
- * @since 5.0.0
+ * @param self an enumeration
+ * @return a List
+ * @since 1.5.0
*/
- public static <K, V> Map<K, V> withCollectedKeys(Iterator<V> values, Function<? super V, K> keyTransform) {
- return withCollectedKeys(values, new LinkedHashMap<>(), keyTransform);
+ public static <T> List<T> toList(Enumeration<T> self) {
+ List<T> answer = new ArrayList<>();
+ while (self.hasMoreElements()) {
+ answer.add(self.nextElement());
+ }
+ return answer;
}
/**
- * Transform Iterable elements into Map entries with values unchanged
- * and keys transformed using the supplied function.
- * The supplied map is used as the destination for transformed entries.
- * <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * def firstLetter = s {@code ->} s[0]
- * assert languages.withCollectedKeys([C:'Clojure'], firstLetter) ==
- * [C:'Clojure', G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
- * </pre>
- * This method is a convenience method for {@link #collectEntries(Iterable, Map, Function, Function)}
- * with the {@code valueTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
+ * Collates this iterable into sub-lists of length <code>size</code>.
+ * Example:
+ * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
+ * def coll = list.collate( 3 )
+ * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]</pre>
*
- * @param values an Iterable that will become the added entry values
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Iterator elements into keys
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self an Iterable
+ * @param size the length of each sub-list in the returned list
+ * @return a List containing the data collated into sub-lists
+ * @since 2.4.0
*/
- public static <K, V> Map<K, V> withCollectedKeys(Iterable<V> values, Map<K, V> collector, Function<? super V, K> keyTransform) {
- return collectEntries(values.iterator(), collector, keyTransform, Function.identity());
+ public static <T> List<List<T>> collate(Iterable<T> self, int size) {
+ return collate(self, size, true);
}
/**
- * Transform Iterable elements into Map entries with values unchanged
- * and keys transformed using the supplied function.
- * <pre class="groovyTestCase">
- * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
- * def firstLetter = s {@code ->} s[0]
- * assert languages.withCollectedKeys(firstLetter) ==
- * [G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
- * </pre>
- * This method is a convenience method for {@link #collectEntries(Iterable, Function, Function)}
- * with the {@code valueTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
+ * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
+ * elements for each subList.
+ * Example:
+ * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4 ]
+ * def coll = list.collate( 3, 1 )
+ * assert coll == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]</pre>
*
- * @param values an Iterable that will become the added entry values
- * @param keyTransform a function for transforming Iterator elements into keys
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self an Iterable
+ * @param size the length of each sub-list in the returned list
+ * @param step the number of elements to step through for each sub-list
+ * @return a List containing the data collated into sub-lists
+ * @since 2.4.0
*/
- public static <K, V> Map<K, V> withCollectedKeys(Iterable<V> values, Function<? super V, K> keyTransform) {
- return withCollectedKeys(values.iterator(), new LinkedHashMap<>(), keyTransform);
+ public static <T> List<List<T>> collate(Iterable<T> self, int size, int step) {
+ return collate(self, size, step, true);
}
/**
- * Transform a Maps' keys leaving the values unchanged.
- * Similar to {@link #withCollectedKeys(Iterable, Map, Function)} but for Maps.
- * <pre class="groovyTestCase">
- * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
- * def firstLetter = s {@code ->} s[0]
- * assert lengths.collectKeys([C:7], firstLetter) == [C:7, G:6, J:4, K:6, S:5]
- * </pre>
+ * Collates this iterable into sub-lists of length <code>size</code>. Any remaining elements in
+ * the iterable after the subdivision will be dropped if <code>keepRemainder</code> is false.
+ * Example:
+ * <pre class="groovyTestCase">def list = [ 1, 2, 3, 4, 5, 6, 7 ]
+ * def coll = list.collate( 3, false )
+ * assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]</pre>
*
- * @param keys a Map
- * @param collector the Map into which the transformed entries are put
- * @param keyTransform a function for transforming Map keys
- * @return the collector with all transformed values added to it
- * @since 5.0.0
+ * @param self an Iterable
+ * @param size the length of each sub-list in the returned list
+ * @param keepRemainder if true, any remaining elements are returned as sub-lists. Otherwise they are discarded
+ * @return a List containing the data collated into sub-lists
+ * @since 2.4.0
*/
- public static <K, V> Map<K, V> collectKeys(Map<K, V> keys, Map<K, V> collector, Function<? super K, K> keyTransform) {
- for (Map.Entry<K, V> entry : keys.entrySet()) {
- addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), entry.getValue()));
- }
- return collector;
+ public static <T> List<List<T>> collate(Iterable<T> self, int size, boolean keepRemainder) {
+ return collate(self, size, size, keepRemainder);
}
/**
- * Transform a Maps' keys leaving the values unchanged.
- * Similar to {@link #withCollectedKeys(Iterable, Function)} but for Maps.
+ * Collates this iterable into sub-lists of length <code>size</code> stepping through the code <code>step</code>
+ * elements for each sub-list. Any remaining elements in the iterable after the subdivision will be dropped if
+ * <code>keepRemainder</code> is false.
+ * Example:
* <pre class="groovyTestCase">
- * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
- * def firstLetter = s {@code ->} s[0]
- * assert lengths.collectKeys(firstLetter) == [G:6, J:4, K:6, S:5]
+ * def list = [ 1, 2, 3, 4 ]
+ * assert list.collate( 2, 2, true ) == [ [ 1, 2 ], [ 3, 4 ] ]
+ * assert list.collate( 3, 1, true ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
+ * assert list.collate( 3, 1, false ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ] ]
* </pre>
*
- * @param keys a Map
- * @param keyTransform a function for transforming Map keys
- * @return a Map of the transformed entries
- * @since 5.0.0
+ * @param self an Iterable
+ * @param size the length of each sub-list in the returned list
+ * @param step the number of elements to step through for each sub-list
+ * @param keepRemainder if true, any remaining elements are returned as sub-lists. Otherwise they are discarded
+ * @return a List containing the data collated into sub-lists
+ * @throws IllegalArgumentException if the step is zero.
+ * @since 2.4.0
*/
- public static <K, V> Map<K, V> collectKeys(Map<K, V> keys, Function<? super K, K> keyTransform) {
- return collectKeys(keys, new LinkedHashMap<>(), keyTransform);
+ public static <T> List<List<T>> collate(Iterable<T> self, int size, int step, boolean keepRemainder) {
+ final List<T> selfList = asList(self);
+ final List<List<T>> answer;
+ if (size <= 0) {
+ answer = new ArrayList<>(1);
+ answer.add(selfList);
+ } else {
+ if (step == 0) throw new IllegalArgumentException("step cannot be zero");
+ final int selfListSize = selfList.size();
+ answer = new ArrayList<>(step < 0 ? 1 : (selfListSize / step + 1));
+ for (int pos = 0; pos < selfListSize && pos > -1; pos += step) {
+ if (!keepRemainder && pos > selfListSize - size) {
+ break;
+ }
+ List<T> element = new ArrayList<>(size);
+ for (int offs = pos; offs < pos + size && offs < selfListSize; offs++) {
+ element.add(selfList.get(offs));
+ }
+ answer.add(element);
+ }
+ }
+ return answer;
}
/**
- * Iterates through this Iterable transforming each item using the closure
- * as a transformer into a map entry, returning the supplied map with all the transformed entries added to it.
- * <pre class="groovyTestCase">
- * def letters = "abc"
- * // collect letters with index
- * assert (0..2).collectEntries( [:] ) { index {@code ->} [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
- * assert (0..2).collectEntries( [4:'d'] ) { index {@code ->}
- * [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
- * </pre>
- * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
- * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
- * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
- * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
+ * Iterates through this aggregate Object transforming each item into a new value using Closure.IDENTITY
+ * as a transformer, basically returning a list of items copied from the original object.
+ * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].iterator().collect()</pre>
*
- * @param self an Iterable
- * @param collector the Map into which the transformed entries are put
- * @param transform the closure used for transforming, which has an item from self as the parameter and
- * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
- * @return the collector with all transformed values added to it
- * @see #collectEntries(Iterator, Map, Closure)
- * @since 1.8.7
+ * @param self an aggregate Object with an Iterator returning its items
+ * @return a Collection of the transformed values
+ * @see Closure#IDENTITY
+ * @since 1.8.5
*/
- public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
- return collectEntries(self.iterator(), collector, transform);
+ @SuppressWarnings("unchecked")
+ public static Collection collect(Object self) {
+ return collect(self, Closure.IDENTITY);
}
/**
- * A variant of collectEntries for Iterators using the identity closure as the
- * transform and a supplied map as the destination of transformed entries.
+ * Iterates through this aggregate Object transforming each item into a new value using the
+ * <code>transform</code> closure, returning a list of transformed values.
+ * Example:
+ * <pre class="groovyTestCase">def list = [1, 'a', 1.23, true ]
+ * def types = list.collect { it.class }
+ * assert types == [Integer, String, BigDecimal, Boolean]</pre>
*
- * @param self an Iterator
- * @param collector the Map into which the transformed entries are put
- * @return the collector with all transformed values added to it
- * @see #collectEntries(Iterable, Map)
- * @since 1.8.7
+ * @param self an aggregate Object with an Iterator returning its items
+ * @param transform the closure used to transform each item of the aggregate object
+ * @return a List of the transformed values
+ * @since 1.0
*/
- public static <K, V> Map<K, V> collectEntries(Iterator<?> self, Map<K, V> collector) {
- return collectEntries(self, collector, Closure.IDENTITY);
+ public static <T> List<T> collect(Object self, Closure<T> transform) {
+ return collect(self, new ArrayList<>(), transform);
}
/**
- * A variant of collectEntries for Iterables using the identity closure as the
- * transform and a supplied map as the destination of transformed entries.
+ * Iterates through this aggregate Object transforming each item into a new value using the <code>transform</code> closure
+ * and adding it to the supplied <code>collector</code>.
*
- * @param self an Iterable
- * @param collector the Map into which the transformed entries are put
+ * @param self an aggregate Object with an Iterator returning its items
+ * @param collector the Collection to which the transformed values are added
+ * @param transform the closure used to transform each item of the aggregate object
* @return the collector with all transformed values added to it
- * @see #collectEntries(Iterator, Map)
- * @since 1.8.7
+ * @since 1.0
*/
- public static <K, V> Map<K, V> collectEntries(Iterable<?> self, Map<K, V> collector) {
- return collectEntries(self.iterator(), collector);
- }
-
- @SuppressWarnings({"rawtypes","unchecked"})
- private static <K, V> void addEntry(Map<K, V> result, Object newEntry) {
- if (newEntry == null) {
- // GROOVY-10893: insert nothing
- } else if (newEntry instanceof Map) {
- leftShift(result, (Map) newEntry);
- } else if (newEntry instanceof List) {
- var list = (List) newEntry;
- // def (key, value) == list
- Object key = list.isEmpty() ? null : list.get(0);
- Object value = list.size() <= 1 ? null : list.get(1);
- leftShift(result, new MapEntry(key, value));
- } else if (newEntry.getClass().isArray()) {
- Object[] array = (Object[]) newEntry;
- // def (key, value) == array.toList()
- Object key = array.length == 0 ? null : array[0];
- Object value = array.length <= 1 ? null : array[1];
- leftShift(result, new MapEntry(key, value));
- } else {
- // given Map.Entry is an interface, we get a proxy which gives us lots
- // of flexibility but sometimes the error messages might be unexpected
- leftShift(result, asType(newEntry, Map.Entry.class));
- }
+ public static <T, C extends Collection<T>> C collect(Object self, C collector, Closure<? extends T> transform) {
+ return collect(InvokerHelper.asIterator(self), collector, transform);
}
/**
- * Finds the first value matching the closure condition.
- *
- * <pre class="groovyTestCase">
- * def numbers = [1, 2, 3]
- * def result = numbers.find { it {@code >} 1}
- * assert result == 2
- * </pre>
+ * Iterates through this Iterator transforming each item into a new value using the
+ * <code>transform</code> closure, returning a list of transformed values.
*
- * @param self an Object with an iterator returning its values
- * @param closure a closure condition
- * @return the first Object found or null if none was found
- * @since 1.0
+ * @param self an Iterator
+ * @param transform the closure used to transform each item
+ * @return a List of the transformed values
+ * @since 2.5.0
*/
- public static Object find(Object self, Closure closure) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
- Object value = iter.next();
- if (bcw.call(value)) {
- return value;
- }
- }
- return null;
+ public static <E, T> List<T> collect(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {
+ return collect(self, new ArrayList<>(), transform);
}
/**
- * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def items = [null, 0, 0.0, false, '', [], 42, 43]
- * assert items.find() == 42
- * </pre>
+ * Iterates through this Iterator transforming each item into a new value using the <code>transform</code> closure
+ * and adding it to the supplied <code>collector</code>.
*
- * @param self an Object with an Iterator returning its values
- * @return the first Object found or null if none was found
- * @since 1.8.1
- * @see Closure#IDENTITY
+ * @param self an Iterator
+ * @param collector the Collection to which the transformed values are added
+ * @param transform the closure used to transform each item
+ * @return the collector with all transformed values added to it
+ * @since 2.5.0
*/
- public static Object find(Object self) {
- return find(self, Closure.IDENTITY);
+ public static <E, T, C extends Collection<T>> C collect(Iterator<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {
+ while (self.hasNext()) {
+ collector.add(transform.call(self.next()));
+ }
+ return collector;
}
/**
- * Finds the first value matching the closure condition. Example:
- * <pre class="groovyTestCase">def list = [1,2,3]
- * assert 2 == list.find { it {@code >} 1 }
- * </pre>
+ * Iterates through this collection transforming each entry into a new value using Closure.IDENTITY
+ * as a transformer, basically returning a list of items copied from the original collection.
+ * <pre class="groovyTestCase">assert [1,2,3] == [1,2,3].collect()</pre>
*
- * @param self a Collection
- * @param closure a closure condition
- * @return the first Object found, in the order of the collections iterator, or null if no element matches
- * @since 1.0
+ * @param self an Iterable
+ * @return a List of the transformed values
+ * @see Closure#IDENTITY
+ * @since 2.5.0
*/
- public static <T> T find(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- for (T value : self) {
- if (bcw.call(value)) {
- return value;
- }
- }
- return null;
+ @SuppressWarnings("unchecked")
+ public static <T> List<T> collect(Iterable<T> self) {
+ return collect(self, (Closure<T>) Closure.IDENTITY);
}
/**
- * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def items = [null, 0, 0.0, false, '', [], 42, 43]
- * assert items.find() == 42
- * </pre>
+ * Iterates through this Iterable transforming each entry into a new value using the <code>transform</code> closure
+ * returning a list of transformed values.
+ * <pre class="groovyTestCase">assert [2,4,6] == [1,2,3].collect { it * 2 }</pre>
*
- * @param self a Collection
- * @return the first Object found or null if none was found
- * @since 1.8.1
- * @see Closure#IDENTITY
+ * @param self an Iterable
+ * @param transform the closure used to transform each item of the collection
+ * @return a List of the transformed values
+ * @since 2.5.0
*/
- public static <T> T find(Collection<T> self) {
- return find(self, Closure.IDENTITY);
+ public static <E, T> List<T> collect(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> transform) {
+ return collect(self.iterator(), transform);
}
/**
- * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns null.
- * <p>
- * <pre class="groovyTestCase">
- * int[] numbers = [1, 2, 3]
- * assert numbers.findResult { if(it {@code >} 1) return it } == 2
- * assert numbers.findResult { if(it {@code >} 4) return it } == null
- * </pre>
+ * Iterates through this collection transforming each value into a new value using the <code>transform</code> closure
+ * and adding it to the supplied <code>collector</code>.
+ * <pre class="groovyTestCase">assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }</pre>
*
- * @param self an Object with an iterator returning its values
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result of the closure
- * @since 1.7.5
+ * @param self an Iterable
+ * @param collector the Collection to which the transformed values are added
+ * @param transform the closure used to transform each item
+ * @return the collector with all transformed values added to it
+ * @since 2.5.0
*/
- public static Object findResult(Object self, Closure condition) {
- for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
- Object value = iter.next();
- Object result = condition.call(value);
- if (result != null) {
- return result;
+ public static <E, T, C extends Collection<T>> C collect(Iterable<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends T> transform) {
+ for (E element : self) {
+ collector.add(transform.call(element));
+ if (transform.getDirective() == Closure.DONE) {
+ break;
}
}
- return null;
+ return collector;
}
/**
- * Treats the object as iterable, iterating through the values it represents and returns the first non-null value, otherwise returns null.
- * <p>
+ * Recursively iterates through this collection transforming each non-Collection value
+ * into a new value using the closure as a transformer. Returns a potentially nested
+ * list of transformed values.
* <pre class="groovyTestCase">
- * class Foo {
- * List items
- * Iterator iterator() {
- * items.iterator()
- * }
- * }
- * assert new Foo(items: [null, 2, 4]).findResult() == 2
- * assert new Foo(items: [null, null]).findResult() == null
- * </pre>
- *
- * @param self an Object with an iterator returning its values
- * @return the first non-null result of the closure
- * @since 4.0.9
+ * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
+ * </pre>
+ *
+ * @param self a collection
+ * @param transform the closure used to transform each item of the collection
+ * @return the resultant collection
+ * @since 1.8.1
*/
- public static Object findResult(Object self) {
- return findResult(self, Closure.IDENTITY);
+ public static List collectNested(Collection self, Closure transform) {
+ return collectNested(self, new ArrayList(self.size()), transform);
}
/**
- * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns the defaultResult.
- * <p>
+ * Recursively iterates through this Iterable transforming each non-Collection value
+ * into a new value using the closure as a transformer. Returns a potentially nested
+ * list of transformed values.
* <pre class="groovyTestCase">
- * int[] numbers = [1, 2, 3]
- * assert numbers.findResult(5) { if(it {@code >} 1) return it } == 2
- * assert numbers.findResult(5) { if(it {@code >} 4) return it } == 5
+ * assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
* </pre>
*
- * @param self an Object with an iterator returning its values
- * @param defaultResult an Object that should be returned if all closure results are null
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result of the closure, otherwise the default value
- * @since 1.7.5
+ * @param self an Iterable
+ * @param transform the closure used to transform each item of the Iterable
+ * @return the resultant list
+ * @since 2.2.0
*/
- public static Object findResult(Object self, Object defaultResult, Closure condition) {
- Object result = findResult(self, condition);
- if (result == null) return defaultResult;
- return result;
+ public static List collectNested(Iterable self, Closure transform) {
+ return collectNested(self, new ArrayList(), transform);
}
/**
- * Treats the object as iterable, iterating through the values it represents and returns the first non-null result, otherwise returns the defaultResult.
- * <p>
+ * Recursively iterates through this Iterable transforming each non-Collection value
+ * into a new value using the <code>transform</code> closure. Returns a potentially nested
+ * collection of transformed values.
* <pre class="groovyTestCase">
- * class Foo {
- * List items
- * Iterator iterator() {
- * items.iterator()
- * }
- * }
- * assert new Foo(items: [null, 2, 4]).findResult(5) == 2
- * assert new Foo(items: [null, null]).findResult(5) == 5
+ * def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 }
+ * assert x == [2,[4,6],[8],[]]
+ * assert x instanceof Vector
* </pre>
*
- * @param self an Object with an iterator returning its values
- * @param defaultResult an Object that should be returned if all elements are null
- * @return the first non-null element, otherwise the default value
- * @since 4.0.9
+ * @param self an Iterable
+ * @param collector an initial Collection to which the transformed values are added
+ * @param transform the closure used to transform each element of the Iterable
+ * @return the collector with all transformed values added to it
+ * @since 2.2.0
*/
- public static Object findResult(Object self, Object defaultResult) {
- Object result = findResult(self, Closure.IDENTITY);
- if (result == null) return defaultResult;
- return result;
+ @SuppressWarnings("unchecked")
+ public static <C extends Collection> C collectNested(Iterable self, C collector, Closure transform) {
+ for (Object element : self) {
+ if (element instanceof Collection) {
+ Collection c = (Collection) element;
+ collector.add(collectNested(c, createSimilarCollection(collector, c.size()), transform));
+ } else {
+ collector.add(transform.call(element));
+ }
+ if (transform.getDirective() == Closure.DONE) {
+ break;
+ }
+ }
+ return collector;
}
/**
- * Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null
- * result is found and returning that result. If all are null, the defaultResult is returned.
+ * Projects each item from a source Iterable to a collection and concatenates (flattens) the resulting collections into a single list.
* <p>
- * Examples:
* <pre class="groovyTestCase">
- * def iter = [1,2,3].iterator()
- * assert "Found 2" == iter.findResult("default") { it {@code >} 1 ? "Found $it" : null }
- * assert "default" == iter.findResult("default") { it {@code >} 3 ? "Found $it" : null }
+ * def nums = 1..10
+ * def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] }
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000]
+ *
+ * def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set
+ * def smallAnimals = animals.collectMany{ it.size() {@code >} 3 ? [] : [it.toLowerCase()] }
+ * assert smallAnimals == ['cat', 'dog']
+ *
+ * def orig = nums as Set
+ * def origPlusIncrements = orig.collectMany{ [it, it+1] }
+ * assert origPlusIncrements.size() == orig.size() * 2
+ * assert origPlusIncrements.unique().size() == orig.size() + 1
* </pre>
*
- * @param self an Iterator
- * @param defaultResult an Object that should be returned if all closure results are null
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result from calling the closure, or the defaultValue
- * @since 2.5.0
+ * @param self an Iterable
+ * @param projection a projecting Closure returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @see #sum(java.lang.Iterable, groovy.lang.Closure)
+ * @since 2.2.0
*/
- public static <S, T, U extends T, V extends T> T findResult(Iterator<S> self, U defaultResult, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> condition) {
- T result = findResult(self, condition);
- if (result == null) return defaultResult;
- return result;
+ public static <T, E> List<T> collectMany(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
}
/**
- * Iterates through the Iterator stopping once the first non-null
- * result is found and returning that result. If all are null, the defaultResult is returned.
+ * Projects each item from a source collection to a result collection and concatenates (flattens) the resulting
+ * collections adding them into the <code>collector</code>.
* <p>
- * Examples:
* <pre class="groovyTestCase">
- * assert [null, 1, 2].iterator().findResult('default') == 1
- * assert [null, null].findResult('default') == 'default'
+ * def animals = ['CAT', 'DOG', 'ELEPHANT']
+ * def smallAnimals = animals.collectMany(['ant', 'bee']){ it.size() > 3 ? [] : [it.toLowerCase()] }
+ * assert smallAnimals == ['ant', 'bee', 'cat', 'dog']
+ *
+ * def nums = 1..5
+ * def origPlusIncrements = nums.collectMany([] as Set){ [it, it+1] }
+ * assert origPlusIncrements.size() == nums.size() + 1
+ *
+ * @groovy.transform.TypeChecked void test() {
+ * LinkedHashSet<String> lhs = ['abc','def'].collectMany(new LinkedHashSet<>()){ it.iterator().collect() }
+ * assert lhs == ['a','b','c','d','e','f'] as Set<String>
+ * }
+ * test()
* </pre>
*
- * @param self an Iterator
- * @param defaultResult an Object that should be returned if all elements are null
- * @return the first non-null result from the iterator, or the defaultValue
- * @since 4.0.9
+ * @param self an Iterable
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting Closure returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) into it
+ * @since 2.2.0
*/
- public static <T, U extends T, V extends T> T findResult(Iterator<U> self, V defaultResult) {
- T result = (T) findResult(self, Closure.IDENTITY);
- return result == null ? defaultResult : result;
+ public static <T, E, C extends Collection<T>> C collectMany(Iterable<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
+ return collectMany(self.iterator(), collector, projection);
}
/**
- * Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null
- * result is found and returning that result. If all results are null, null is returned.
+ * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
+ * collections adding them into the <code>collector</code>.
+ * <p>
+ * <pre class="groovyTestCase">
+ * def map = [bread:3, milk:5, butter:2]
+ * def result = map.collectMany(['x']){ k, v {@code ->} if (k.startsWith('b')) k.toList() }
+ * assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
+ * </pre>
*
- * @param self an Iterator
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result from calling the closure, or null
- * @since 2.5.0
+ * @param self a map
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting Closure returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) to it
+ * @since 1.8.8
*/
- public static <T, U> T findResult(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
- while (self.hasNext()) {
- U next = self.next();
- T result = condition.call(next);
- if (result != null) {
- return result;
- }
+ public static <T, K, V, C extends Collection<T>> C collectMany(Map<K, V> self, C collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends Collection<? extends T>> projection) {
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ var items = callClosureForMapEntry(projection, entry);
+ if (items != null && !items.isEmpty()) collector.addAll(items);
}
- return null;
+ return collector;
}
/**
- * Iterates through the Iterator stopping once the first non-null
- * result is found and returning that result. If all results are null, null is returned.
+ * Projects each item from a source map to a result collection and concatenates (flattens) the resulting
+ * collections adding them into a collection.
+ * <p>
+ * <pre class="groovyTestCase">
+ * def map = [bread:3, milk:5, butter:2]
+ * def result = map.collectMany{ k, v {@code ->} k.startsWith('b') ? k.toList() : [] }
+ * assert result == ['b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
+ * </pre>
*
- * @param self an Iterator
- * @return the first non-null result from the iterator, or null
- * @since 4.0.9
+ * @param self a map
+ * @param projection a projecting Closure returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @since 1.8.8
*/
- public static <T> T findResult(Iterator<T> self) {
- return (T) findResult(self, Closure.IDENTITY);
+ public static <T, K, V> List<T> collectMany(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
}
/**
- * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
- * result is found and returning that result. If all are null, the defaultResult is returned.
+ * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
* <p>
- * Examples:
* <pre class="groovyTestCase">
- * def list = [1,2,3]
- * assert "Found 2" == list.findResult("default") { it {@code >} 1 ? "Found $it" : null }
- * assert "default" == list.findResult("default") { it {@code >} 3 ? "Found $it" : null }
+ * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
+ * def squaresAndCubesOfEvens = numsIter.collectMany{ if (it % 2 == 0) [it**2, it**3] }
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
+ * </pre>
+ * <p>
+ * <pre class="groovyTestCase">
+ * var letters = 'a'..'z'
+ * var pairs = letters.collectMany{ a ->
+ * letters.collectMany{ b ->
+ * if (a != b) ["$a$b"]
+ * }
+ * }
+ * assert pairs.join(',').matches('ab,ac,ad,.*,zw,zx,zy')
* </pre>
*
- * @param self an Iterable
- * @param defaultResult an Object that should be returned if all closure results are null
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result from calling the closure, or the defaultValue
- * @since 2.5.0
+ * @param self an iterator
+ * @param collector an initial collection to add the projected items to
+ * @param projection a projecting Closure returning a collection of items
+ * @return the collector with the projected collections concatenated (flattened) to it
+ * @see #sum(Iterator, groovy.lang.Closure)
+ * @since 1.8.1
*/
- public static <S, T, U extends T, V extends T> T findResult(Iterable<S> self, U defaultResult, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> condition) {
- T result = findResult(self, condition);
- if (result == null) return defaultResult;
- return result;
+ public static <T, E, C extends Collection<T>> C collectMany(Iterator<E> self, C collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
+ while (self.hasNext()) {
+ E element = self.next();
+ var items = projection.call(element);
+ if (items != null) collector.addAll(items);
+ }
+ return collector;
}
/**
- * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
- * result is found and returning that result. If all are null, the defaultResult is returned.
+ * Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
* <p>
- * Examples:
* <pre class="groovyTestCase">
- * assert [null, 1, 2].findResult('default') == 1
- * assert [null, null].findResult('default') == 'default'
- * </pre>
- *
- * @param self an Iterable
- * @param defaultResult an Object that should be returned if all elements in the iterable are null
- * @return the first non-null element from the iterable, or the defaultValue
- * @since 4.0.9
+ * def numsIter = [1, 2, 3, 4, 5, 6].iterator()
+ * def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
+ * assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
+ * </pre>
+ *
+ * @param self an iterator
+ * @param projection a projecting Closure returning a collection of items
+ * @return a list created from the projected collections concatenated (flattened) together
+ * @see #collectMany(Iterator, Collection, groovy.lang.Closure)
+ * @since 1.8.1
*/
- public static <T, U extends T, V extends T> T findResult(Iterable<U> self, V defaultResult) {
- T result = (T) findResult(self, Closure.IDENTITY);
- if (result == null) return defaultResult;
- return result;
+ public static <T, E> List<T> collectMany(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<? extends Collection<? extends T>> projection) {
+ return collectMany(self, new ArrayList<>(), projection);
}
/**
- * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
- * result is found and returning that result. If all results are null, null is returned.
+ * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
+ * returning the <code>collector</code> with all transformed values added to it.
+ * <pre class="groovyTestCase">assert [a:1, b:2].collect( [] as HashSet ) { key, value {@code ->} key*value } == ["a", "bb"] as Set
+ * assert [3:20, 2:30].collect( [] as HashSet ) { entry {@code ->} entry.key * entry.value } == [60] as Set</pre>
*
- * @param self an Iterable
- * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
- * @return the first non-null result from calling the closure, or null
- * @since 2.5.0
+ * @param self a Map
+ * @param collector the Collection to which transformed values are added
+ * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
+ * @return the collector with all transformed values added to it
+ * @since 1.0
*/
- public static <T, U> T findResult(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
- return findResult(self.iterator(), condition);
+ public static <T, K, V, C extends Collection<T>> C collect(Map<K, V> self, C collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<? extends T> transform) {
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ collector.add(callClosureForMapEntry(transform, entry));
+ }
+ return collector;
}
/**
- * Iterates through the Iterable stopping once the first non-null
- * result is found and returning that result. If all results are null, null is returned.
+ * Iterates through this Map transforming each map entry into a new value using the <code>transform</code> closure
+ * returning a list of transformed values.
+ * <pre class="groovyTestCase">assert [a:1, b:2].collect { key, value {@code ->} key*value } == ["a", "bb"]
+ * assert [3:20, 2:30].collect { entry {@code ->} entry.key * entry.value } == [60, 60]</pre>
*
- * @param self an Iterable
- * @return the first non-null element from the iterable, or null
- * @since 4.0.9
+ * @param self a Map
+ * @param transform the transformation closure which can take one (Map.Entry) or two (key, value) parameters
+ * @return the resultant list of transformed values
+ * @since 1.0
*/
- public static <T> T findResult(Iterable<T> self) {
- return (T) findResult(self.iterator(), Closure.IDENTITY);
+ public static <T, K, V> List<T> collect(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> transform) {
+ return collect(self, new ArrayList<>(self.size()), transform);
}
/**
- * Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned.
- * If the closure takes two parameters, the entry key and value are passed.
- * If the closure takes one parameter, the Map.Entry object is passed.
+ * Iterates through this Map transforming each map entry using the <code>transform</code> closure
+ * returning a map of the transformed entries.
* <pre class="groovyTestCase">
- * assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
- * assert null == [a:1, b:3].findResult { if (it.value == 9) return "Found ${it.key}:${it.value}" }
- * assert "Found a:1" == [a:1, b:3].findResult { k, v {@code ->} if (k.size() + v == 2) return "Found $k:$v" }
+ * assert [a:1, b:2].collectEntries( [:] ) { k, v {@code ->} [v, k] } == [1:'a', 2:'b']
+ * assert [a:1, b:2].collectEntries( [30:'C'] ) { key, value {@code ->}
+ * [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
* </pre>
+ * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
+ * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
+ * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
+ * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
*
* @param self a Map
- * @param condition a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
- * @return the first non-null result collected by calling the closure, or null if no such result was found
- * @since 1.7.5
+ * @param collector the Map into which the transformed entries are put
+ * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return the collector with all transformed values added to it
+ * @see #collect(Map, Collection, Closure)
+ * @since 1.7.9
*/
- public static <T, K, V> T findResult(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> condition) {
- for (Map.Entry<K, V> entry : self.entrySet()) {
- T result = callClosureForMapEntry(condition, entry);
- if (result != null) {
- return result;
- }
+ public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Map<K, V> collector, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
+ for (Map.Entry<X, Y> entry : self.entrySet()) {
+ addEntry(collector, callClosureForMapEntry(transform, entry));
}
- return null;
+ return collector;
}
/**
- * Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned.
- * If the closure takes two parameters, the entry key and value are passed.
- * If the closure takes one parameter, the Map.Entry object is passed.
+ * Iterates through this Map transforming each entry using the <code>transform</code> closure
+ * and returning a map of the transformed entries.
* <pre class="groovyTestCase">
- * assert "Found b:3" == [a:1, b:3].findResult("default") { if (it.value == 3) return "Found ${it.key}:${it.value}" }
- * assert "default" == [a:1, b:3].findResult("default") { if (it.value == 9) return "Found ${it.key}:${it.value}" }
- * assert "Found a:1" == [a:1, b:3].findResult("default") { k, v {@code ->} if (k.size() + v == 2) return "Found $k:$v" }
+ * assert [a:1, b:2].collectEntries { key, value {@code ->} [value, key] } == [1:'a', 2:'b']
+ * assert [a:1, b:2].collectEntries { key, value {@code ->}
+ * [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
* </pre>
+ * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
+ * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
+ * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
+ * If your Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
*
- * @param self a Map
- * @param defaultResult an Object that should be returned if all closure results are null
- * @param condition a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
- * @return the first non-null result collected by calling the closure, or the defaultResult if no such result was found
- * @since 1.7.5
+ * @param self a Map
+ * @param transform the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return a Map of the transformed entries
+ * @see #collect(Map, Collection, Closure)
+ * @since 1.7.9
*/
- public static <T, U extends T, V extends T, A, B> T findResult(Map<A, B> self, U defaultResult, @ClosureParams(MapEntryOrKeyValue.class) Closure<V> condition) {
- T result = findResult(self, condition);
- if (result == null) return defaultResult;
- return result;
+ @SuppressWarnings("unchecked")
+ public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
+ return collectEntries(self, (Map) createSimilarMap(self), transform);
}
/**
- * Iterates through the Iterable transforming items using the supplied closure
- * and collecting any non-null results.
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def list = [1,2,3]
- * def result = list.findResults { it {@code >} 1 ? "Found $it" : null }
- * assert result == ["Found 2", "Found 3"]
- * </pre>
+ * A variant of collectEntries for Iterators.
*
- * @param self an Iterable
- * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded
- * @return the list of non-null transformed values
- * @since 2.2.0
+ * @param self an Iterator
+ * @param transform the closure used for transforming, which has an item from self as the parameter and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return a Map of the transformed entries
+ * @see #collectEntries(Iterable, Closure)
+ * @since 1.8.7
*/
- public static <T, U> Collection<T> findResults(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
- return findResults(self.iterator(), filteringTransform);
+ public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
+ return collectEntries(self, new LinkedHashMap<>(), transform);
}
/**
- * Iterates through the Iterable collecting any non-null results.
- * <p>
- * Example:
+ * Iterates through this Iterable transforming each item using the <code>transform</code> closure
+ * and returning a map of the resulting transformed entries.
* <pre class="groovyTestCase">
- * assert [1, null, 2, null, 3].findResults() == [1, 2, 3]
+ * def letters = "abc"
+ * // collect letters with index using list style
+ * assert (0..2).collectEntries { index {@code ->} [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
+ * // collect letters with index using map style
+ * assert (0..2).collectEntries { index {@code ->} [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
* </pre>
+ * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
+ * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
+ * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
*
- * @param self an Iterable
- * @return the list of non-null values
- * @since 4.0.9
+ * @param self an Iterable
+ * @param transform the closure used for transforming, which has an item from self as the parameter and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return a Map of the transformed entries
+ * @see #collectEntries(Iterator, Closure)
+ * @since 1.8.7
*/
- public static <T> Collection<T> findResults(Iterable<T> self) {
- return findResults(self.iterator(), Closure.IDENTITY);
+ public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
+ return collectEntries(self.iterator(), transform);
}
/**
- * Iterates through the Iterator transforming items using the supplied closure
- * and collecting any non-null results.
+ * A variant of collectEntries for Iterators using the identity closure as the transform.
*
- * @param self an Iterator
- * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded
- * @return the list of non-null transformed values
- * @since 2.5.0
+ * @param self an Iterator
+ * @return a Map of the transformed entries
+ * @see #collectEntries(Iterable)
+ * @since 1.8.7
*/
- public static <T, U> Collection<T> findResults(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
- List<T> result = new ArrayList<>();
- while (self.hasNext()) {
- U value = self.next();
- T transformed = filteringTransform.call(value);
- if (transformed != null) {
- result.add(transformed);
- }
- }
- return result;
+ public static <K, V> Map<K, V> collectEntries(Iterator<?> self) {
+ return collectEntries(self, Closure.IDENTITY);
}
/**
- * Iterates through the Iterator collecting any non-null results.
+ * A variant of collectEntries for Iterable objects using the identity closure as the transform.
+ * The source Iterable should contain a list of <code>[key, value]</code> tuples or <code>Map.Entry</code> objects.
+ * <pre class="groovyTestCase">
+ * def nums = [1, 10, 100, 1000]
+ * def tuples = nums.collect{ [it, it.toString().size()] }
+ * assert tuples == [[1, 1], [10, 2], [100, 3], [1000, 4]]
+ * def map = tuples.collectEntries()
+ * assert map == [1:1, 10:2, 100:3, 1000:4]
+ * </pre>
*
- * @param self an Iterator
- * @return the list of non-null values
- * @since 4.0.9
+ * @param self an Iterable
+ * @return a Map of the transformed entries
+ * @see #collectEntries(Iterator)
+ * @since 1.8.7
*/
- public static <T> Collection<T> findResults(Iterator<T> self) {
- return findResults(self, Closure.IDENTITY);
+ public static <K, V> Map<K, V> collectEntries(Iterable<?> self) {
+ return collectEntries(self.iterator());
}
/**
- * Iterates through the map transforming items using the supplied closure
- * and collecting any non-null results.
- * If the closure takes two parameters, the entry key and value are passed.
- * If the closure takes one parameter, the Map.Entry object is passed.
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def map = [a:1, b:2, hi:2, cat:3, dog:2]
- * def result = map.findResults { k, v {@code ->} k.size() == v ? "Found $k:$v" : null }
- * assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
- * </pre>
+ * A variant of collectEntries for Iterators using a supplied map as the destination of transformed entries.
*
- * @param self a Map
- * @param filteringTransform a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discarded
- * @return the list of non-null transformed values
- * @since 1.8.1
+ * @param self an Iterator
+ * @param collector the Map into which the transformed entries are put
+ * @param transform the closure used for transforming, which has an item from self as the parameter and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return the collector with all transformed values added to it
+ * @since 1.8.7
+ */
+ public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
+ while (self.hasNext()) {
+ E element = self.next();
+ addEntry(collector, transform.call(element));
+ }
+ return collector;
+ }
+
+ /**
+ * A variant of collectEntries for Iterators with separate functions for transforming the keys and values.
+ * The supplied collector map is used as the destination for transformed entries.
+ *
+ * @param self an Iterator
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Iterator elements into keys
+ * @param valueTransform a function for transforming Iterator elements into values
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <T, K, V> Collection<T> findResults(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> filteringTransform) {
- List<T> result = new ArrayList<>();
- for (Map.Entry<K, V> entry : self.entrySet()) {
- T transformed = callClosureForMapEntry(filteringTransform, entry);
- if (transformed != null) {
- result.add(transformed);
- }
+ public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
+ while (self.hasNext()) {
+ E element = self.next();
+ addEntry(collector, Tuple2.tuple(keyTransform.apply(element), valueTransform.apply(element)));
}
- return result;
+ return collector;
}
/**
- * Finds the first entry matching the closure condition.
- * If the closure takes two parameters, the entry key and value are passed.
- * If the closure takes one parameter, the Map.Entry object is passed.
- * <pre class="groovyTestCase">assert [a:1, b:3].find { it.value == 3 }.key == "b"</pre>
+ * A variant of collectEntries for Iterators with separate functions for transforming the keys and values.
*
- * @param self a Map
- * @param closure a 1 or 2 arg Closure condition
- * @return the first Object found
- * @since 1.0
+ * @param self an Iterator
+ * @param keyTransform a function for transforming Iterator elements into keys
+ * @param valueTransform a function for transforming Iterator elements into values
+ * @return a Map of the transformed entries
+ * @since 5.0.0
*/
- public static <K, V> Map.Entry<K, V> find(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (bcw.callForMap(entry)) {
- return entry;
- }
- }
- return null;
+ public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
+ return collectEntries(self, new LinkedHashMap<>(), keyTransform, valueTransform);
}
/**
- * Finds all entries matching the closure condition. If the
- * closure takes one parameter then it will be passed the Map.Entry.
- * Otherwise if the closure should take two parameters, which will be
- * the key and the value.
- * <p>
- * If the <code>self</code> map is one of TreeMap, LinkedHashMap, Hashtable
- * or Properties, the returned Map will preserve that type, otherwise a HashMap will
- * be returned.
- * <p>
- * Example usage:
+ * A variant of collectEntries for Iterables with separate functions for transforming the keys and values.
+ * The supplied collector map is used as the destination for transformed entries.
* <pre class="groovyTestCase">
- * def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
- * assert result.every { it instanceof Map.Entry }
- * assert result*.key == ["b", "c"]
- * assert result*.value == [2, 4]
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * assert languages.collectEntries([clojure:7], String::toLowerCase, String::size) ==
+ * [clojure:7, groovy:6, java:4, kotlin:6, scala:5]
* </pre>
*
- * @param self a Map
- * @param closure a 1 or 2 arg Closure condition applying on the entries
- * @return a new subMap
- * @since 1.0
+ * @param self an Iterable
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Iterable elements into keys
+ * @param valueTransform a function for transforming Iterable elements into values
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <K, V> Map<K, V> findAll(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure closure) {
- Map<K, V> answer = createSimilarMap(self);
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (bcw.callForMap(entry)) {
- answer.put(entry.getKey(), entry.getValue());
- }
- }
- return answer;
+ public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Map<K, V> collector, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
+ return collectEntries(self.iterator(), collector, keyTransform, valueTransform);
}
/**
- * Finds all values matching the closure condition.
- * <pre class="groovyTestCase">assert ([2,4] as Set) == ([1,2,3,4] as Set).findAll { it % 2 == 0 }</pre>
+ * A variant of collectEntries for Iterables with separate functions for transforming the keys and values.
+ * <pre class="groovyTestCase">
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * assert languages.collectEntries(String::toLowerCase, String::size) ==
+ * [groovy:6, java:4, kotlin:6, scala:5]
+ * </pre>
*
- * @param self a Set
- * @param closure a closure condition
- * @return a Set of matching values
- * @since 2.4.0
+ * @param self an Iterable
+ * @param keyTransform a function for transforming Iterable elements into keys
+ * @param valueTransform a function for transforming Iterable elements into values
+ * @return a Map of the transformed entries
+ * @since 5.0.0
*/
- public static <T> Set<T> findAll(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (Set<T>) findAll((Collection<T>) self, closure);
+ public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
+ return collectEntries(self.iterator(), new LinkedHashMap<>(), keyTransform, valueTransform);
}
/**
- * Finds all values matching the closure condition.
- * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
+ * A variant of collectEntries for Maps with separate functions for transforming the keys and values.
+ * The supplied collector map is used as the destination for transformed entries.
*
- * @param self a List
- * @param closure a closure condition
- * @return a List of matching values
- * @since 2.4.0
+ * @param self a Map
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Map keys
+ * @param valueTransform a function for transforming Map values
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <T> List<T> findAll(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (List<T>) findAll((Collection<T>) self, closure);
+ public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Map<K, V> collector, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform) {
+ for (Map.Entry<X, Y> entry : self.entrySet()) {
+ addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), valueTransform.apply(entry.getValue())));
+ }
+ return collector;
}
/**
- * Finds all values matching the closure condition.
- * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
+ * A variant of collectEntries for Maps with separate functions for transforming the keys and values.
*
- * @param self a Collection
- * @param closure a closure condition
- * @return a Collection of matching values
- * @since 1.5.6
+ * @param self a Map
+ * @param keyTransform a function for transforming Map keys
+ * @param valueTransform a function for transforming Map values
+ * @return a Map of the transformed entries
+ * @since 5.0.0
*/
- public static <T> Collection<T> findAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return findMany(createSimilarCollection(self), self.iterator(), closure);
+ public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform) {
+ return collectEntries(self, new LinkedHashMap<>(), keyTransform, valueTransform);
}
/**
- * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
- * assert items.findAll() == [1, 2, true, 'foo', [4, 5]] as Set
- * </pre>
+ * A variant of withCollectedValues for Iterators.
*
- * @param self a Set
- * @return a Set of the truthy values
- * @since 2.4.0
- * @see Closure#IDENTITY
+ * @param keys an Iterator
+ * @param collector the Map into which the transformed entries are put
+ * @param valueTransform a function for transforming Iterator elements into values
+ * @return the collector with all transformed values added to it
+ * @see #withCollectedValues(Iterable, Map, Function)
+ * @since 5.0.0
*/
- public static <T> Set<T> findAll(Set<T> self) {
- return findAll(self, Closure.IDENTITY);
+ public static <K, V> Map<K, V> withCollectedValues(Iterator<K> keys, Map<K, V> collector, Function<? super K, V> valueTransform) {
+ return collectEntries(keys, collector, Function.identity(), valueTransform);
}
/**
- * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
- * <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
- * </pre>
+ * A variant of withCollectedValues for Iterators.
*
- * @param self a List
- * @return a List of the truthy values
- * @since 2.4.0
- * @see Closure#IDENTITY
+ * @param keys an Iterator
+ * @param valueTransform a function for transforming Iterator elements into values
+ * @return a Map of the transformed entries
+ * @see #withCollectedValues(Iterable, Function)
+ * @since 5.0.0
*/
- public static <T> List<T> findAll(List<T> self) {
- return findAll(self, Closure.IDENTITY);
+ public static <K, V> Map<K, V> withCollectedValues(Iterator<K> keys, Function<? super K, V> valueTransform) {
+ return withCollectedValues(keys, new LinkedHashMap<>(), valueTransform);
}
/**
- * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
+ * Transform Iterable elements into Map entries with keys unchanged
+ * and values transformed using the supplied function.
+ * The supplied collector map is used as the destination for transformed entries.
* <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * assert languages.withCollectedValues([Clojure:7], String::size) ==
+ * [Clojure:7, Groovy:6, Java:4, Kotlin:6, Scala:5]
* </pre>
+ * This method is a convenience method for {@link #collectEntries(Iterable, Map, Function, Function)}
+ * with the {@code keyTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
*
- * @param self a Collection
- * @return a Collection of the truthy values
- * @since 1.8.1
- * @see Closure#IDENTITY
+ * @param keys an Iterable
+ * @param collector the Map into which the transformed entries are put
+ * @param valueTransform a function for transforming Iterable elements into values
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <T> Collection<T> findAll(Collection<T> self) {
- return findAll(self, Closure.IDENTITY);
+ public static <K, V> Map<K, V> withCollectedValues(Iterable<K> keys, Map<K, V> collector, Function<? super K, V> valueTransform) {
+ return collectEntries(keys.iterator(), collector, Function.identity(), valueTransform);
}
/**
- * Finds all items matching the closure condition.
+ * Transform Iterable elements into Map entries with keys unchanged
+ * and values transformed using the supplied function.
+ * <pre class="groovyTestCase">
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * assert languages.withCollectedValues(String::size) ==
+ * [Groovy:6, Java:4, Kotlin:6, Scala:5]
+ * </pre>
+ * This method is a convenience method for {@link #collectEntries(Iterable, Function, Function)}
+ * with the {@code keyTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
*
- * @param self an Object with an Iterator returning its values
- * @param closure a closure condition
- * @return a List of the values found
- * @since 1.6.0
+ * @param keys an Iterable
+ * @param valueTransform a function for transforming Iterable elements into values
+ * @return a Map of the transformed entries
+ * @since 5.0.0
*/
- @SuppressWarnings("unchecked")
- public static List findAll(Object self, Closure closure) {
- return findMany(new ArrayList(), InvokerHelper.asIterator(self), closure);
+ public static <K, V> Map<K, V> withCollectedValues(Iterable<K> keys, Function<? super K, V> valueTransform) {
+ return withCollectedValues(keys.iterator(), new LinkedHashMap<>(), valueTransform);
}
/**
- * Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth).
- * <p>
- * Example:
+ * Transform a Maps' values leaving the keys unchanged.
+ * Similar to {@link #withCollectedValues(Iterable, Map, Function)} but for Maps.
* <pre class="groovyTestCase">
- * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
- * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
+ * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
+ * def squared = e {@code ->} e ** 2
+ * assert lengths.collectValues([Clojure:49], squared) ==
+ * [Clojure:49, Groovy:36, Java:16, Kotlin:36, Scala:25]
* </pre>
*
- * @param self an Object with an Iterator returning its values
- * @return a List of the truthy values
- * @since 1.8.1
- * @see Closure#IDENTITY
- */
- public static List findAll(Object self) {
- return findAll(self, Closure.IDENTITY);
- }
-
- static <T, C extends Collection<T>> C findMany(C collector, Iterator<? extends T> iter, Closure<?> closure) {
- BooleanClosureWrapper test = new BooleanClosureWrapper(closure);
- while (iter.hasNext()) {
- T value = iter.next();
- if (test.call(value)) {
- collector.add(value);
- }
+ * @param keys a Map
+ * @param collector the Map into which the transformed entries are put
+ * @param valueTransform a function for transforming Map values
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
+ */
+ public static <K, V> Map<K, V> collectValues(Map<K, V> keys, Map<K, V> collector, Function<? super V, V> valueTransform) {
+ for (Map.Entry<K, V> entry : keys.entrySet()) {
+ addEntry(collector, Tuple2.tuple(entry.getKey(), valueTransform.apply(entry.getValue())));
}
return collector;
}
/**
- * Returns <tt>true</tt> if this iterable contains the item.
+ * Transform a Maps' values leaving the keys unchanged.
+ * Similar to {@link #withCollectedValues(Iterable, Function)} but for Maps.
+ * <pre class="groovyTestCase">
+ * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
+ * def squared = e {@code ->} e ** 2
+ * assert lengths.collectValues(squared) == [Groovy:36, Java:16, Kotlin:36, Scala:25]
+ * </pre>
*
- * @param self an Iterable to be checked for containment
- * @param item an Object to be checked for containment in this iterable
- * @return <tt>true</tt> if this iterable contains the item
- * @see Collection#contains(Object)
- * @since 2.4.0
+ * @param keys a Map
+ * @param valueTransform a function for transforming Map values
+ * @return a Map of the transformed entries
+ * @since 5.0.0
*/
- public static boolean contains(Iterable self, Object item) {
- for (Object e : self) {
- if (Objects.equals(item, e)) {
- return true;
- }
- }
- return false;
+ public static <K, V> Map<K, V> collectValues(Map<K, V> keys, Function<? super V, V> valueTransform) {
+ return collectValues(keys, new LinkedHashMap<>(), valueTransform);
}
/**
- * Returns <tt>true</tt> if this iterable contains all the elements
- * in the specified array.
+ * A variant of withCollectedKeys for Iterators.
*
- * @param self an Iterable to be checked for containment
- * @param items array to be checked for containment in this iterable
- * @return <tt>true</tt> if this collection contains all the elements
- * in the specified array
- * @see Collection#containsAll(Collection)
- * @since 2.4.0
+ * @param values an Iterator
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Iterator elements into values
+ * @return the collector with all transformed values added to it
+ * @see #withCollectedKeys(Iterable, Map, Function)
+ * @since 5.0.0
*/
- public static boolean containsAll(Iterable<?> self, Object[] items) {
- return asCollection(self).containsAll(Arrays.asList(items));
+ public static <K, V> Map<K, V> withCollectedKeys(Iterator<V> values, Map<K, V> collector, Function<? super V, K> keyTransform) {
+ return collectEntries(values, collector, keyTransform, Function.identity());
}
/**
- * Modifies this collection by removing its elements that are contained
- * within the specified object array.
- *
- * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
- * containing items which don't match some criteria while leaving the original collection unchanged.
+ * A variant of withCollectedKeys for Iterators.
*
- * @param self a Collection to be modified
- * @param items array containing elements to be removed from this collection
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see Collection#removeAll(Collection)
- * @since 1.7.2
+ * @param values an Iterator
+ * @param keyTransform a function for transforming Iterator elements into values
+ * @return a Map of the transformed entries
+ * @see #withCollectedKeys(Iterable, Function)
+ * @since 5.0.0
*/
- @SuppressWarnings("unchecked")
- public static boolean removeAll(Collection self, Object[] items) {
- Collection pickFrom = new TreeSet(new NumberAwareComparator());
- pickFrom.addAll(Arrays.asList(items));
- return self.removeAll(pickFrom);
+ public static <K, V> Map<K, V> withCollectedKeys(Iterator<V> values, Function<? super V, K> keyTransform) {
+ return withCollectedKeys(values, new LinkedHashMap<>(), keyTransform);
}
/**
- * Modifies this collection so that it retains only its elements that are contained
- * in the specified array. In other words, removes from this collection all of
- * its elements that are not contained in the specified array.
- *
- * See also <code>grep</code> and <code>findAll</code> when wanting to produce a new list
- * containing items which match some specified items but leaving the original collection unchanged.
+ * Transform Iterable elements into Map entries with values unchanged
+ * and keys transformed using the supplied function.
+ * The supplied map is used as the destination for transformed entries.
+ * <pre class="groovyTestCase">
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * def firstLetter = s {@code ->} s[0]
+ * assert languages.withCollectedKeys([C:'Clojure'], firstLetter) ==
+ * [C:'Clojure', G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
+ * </pre>
+ * This method is a convenience method for {@link #collectEntries(Iterable, Map, Function, Function)}
+ * with the {@code valueTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
*
- * @param self a Collection to be modified
- * @param items array containing elements to be retained from this collection
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see Collection#retainAll(Collection)
- * @since 1.7.2
+ * @param values an Iterable that will become the added entry values
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Iterator elements into keys
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- @SuppressWarnings("unchecked")
- public static boolean retainAll(Collection self, Object[] items) {
- Collection pickFrom = new TreeSet(new NumberAwareComparator());
- pickFrom.addAll(Arrays.asList(items));
- return self.retainAll(pickFrom);
+ public static <K, V> Map<K, V> withCollectedKeys(Iterable<V> values, Map<K, V> collector, Function<? super V, K> keyTransform) {
+ return collectEntries(values.iterator(), collector, keyTransform, Function.identity());
}
/**
- * Modifies this collection so that it retains only its elements
- * that are matched according to the specified closure condition. In other words,
- * removes from this collection all of its elements that don't match.
- *
- * <pre class="groovyTestCase">def list = ['a', 'b']
- * list.retainAll { it == 'b' }
- * assert list == ['b']</pre>
- *
- * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
- * containing items which match some criteria but leaving the original collection unchanged.
+ * Transform Iterable elements into Map entries with values unchanged
+ * and keys transformed using the supplied function.
+ * <pre class="groovyTestCase">
+ * def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
+ * def firstLetter = s {@code ->} s[0]
+ * assert languages.withCollectedKeys(firstLetter) ==
+ * [G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
+ * </pre>
+ * This method is a convenience method for {@link #collectEntries(Iterable, Function, Function)}
+ * with the {@code valueTransform} replaced by {@code Function.identity()} or {Closure.IDENTITY}.
*
- * @param self a Collection to be modified
- * @param condition a closure condition
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see Iterator#remove()
- * @since 1.7.2
+ * @param values an Iterable that will become the added entry values
+ * @param keyTransform a function for transforming Iterator elements into keys
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <T> boolean retainAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
- Iterator iter = InvokerHelper.asIterator(self);
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
- boolean result = false;
- while (iter.hasNext()) {
- Object value = iter.next();
- if (!bcw.call(value)) {
- iter.remove();
- result = true;
- }
- }
- return result;
+ public static <K, V> Map<K, V> withCollectedKeys(Iterable<V> values, Function<? super V, K> keyTransform) {
+ return withCollectedKeys(values.iterator(), new LinkedHashMap<>(), keyTransform);
}
/**
- * Modifies this map so that it retains only its elements that are matched
- * according to the specified closure condition. In other words, removes from
- * this map all of its elements that don't match. If the closure takes one
- * parameter then it will be passed the <code>Map.Entry</code>. Otherwise the closure should
- * take two parameters, which will be the key and the value.
- *
- * <pre class="groovyTestCase">def map = [a:1, b:2]
- * map.retainAll { k,v {@code ->} k == 'b' }
- * assert map == [b:2]</pre>
- *
- * See also <code>findAll</code> when wanting to produce a new map containing items
- * which match some criteria but leaving the original map unchanged.
+ * Transform a Maps' keys leaving the values unchanged.
+ * Similar to {@link #withCollectedKeys(Iterable, Map, Function)} but for Maps.
+ * <pre class="groovyTestCase">
+ * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
+ * def firstLetter = s {@code ->} s[0]
+ * assert lengths.collectKeys([C:7], firstLetter) == [C:7, G:6, J:4, K:6, S:5]
+ * </pre>
*
- * @param self a Map to be modified
- * @param condition a 1 or 2 arg Closure condition applying on the entries
- * @return <tt>true</tt> if this map changed as a result of the call
- * @since 2.5.0
+ * @param keys a Map
+ * @param collector the Map into which the transformed entries are put
+ * @param keyTransform a function for transforming Map keys
+ * @return the collector with all transformed values added to it
+ * @since 5.0.0
*/
- public static <K, V> boolean retainAll(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure condition) {
- Iterator<Map.Entry<K, V>> iter = self.entrySet().iterator();
- BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
- boolean result = false;
- while (iter.hasNext()) {
- Map.Entry<K, V> entry = iter.next();
- if (!bcw.callForMap(entry)) {
- iter.remove();
- result = true;
- }
+ public static <K, V> Map<K, V> collectKeys(Map<K, V> keys, Map<K, V> collector, Function<? super K, K> keyTransform) {
+ for (Map.Entry<K, V> entry : keys.entrySet()) {
+ addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), entry.getValue()));
}
- return result;
+ return collector;
}
/**
- * Modifies this collection by removing the elements that are matched according
- * to the specified closure condition.
+ * Transform a Maps' keys leaving the values unchanged.
+ * Similar to {@link #withCollectedKeys(Iterable, Function)} but for Maps.
+ * <pre class="groovyTestCase">
+ * def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
+ * def firstLetter = s {@code ->} s[0]
+ * assert lengths.collectKeys(firstLetter) == [G:6, J:4, K:6, S:5]
+ * </pre>
*
- * <pre class="groovyTestCase">def list = ['a', 'b']
- * list.removeAll { it == 'b' }
- * assert list == ['a']</pre>
+ * @param keys a Map
+ * @param keyTransform a function for transforming Map keys
+ * @return a Map of the transformed entries
+ * @since 5.0.0
+ */
+ public static <K, V> Map<K, V> collectKeys(Map<K, V> keys, Function<? super K, K> keyTransform) {
+ return collectKeys(keys, new LinkedHashMap<>(), keyTransform);
+ }
+
+ /**
+ * Iterates through this Iterable transforming each item using the closure
+ * as a transformer into a map entry, returning the supplied map with all the transformed entries added to it.
+ * <pre class="groovyTestCase">
+ * def letters = "abc"
+ * // collect letters with index
+ * assert (0..2).collectEntries( [:] ) { index {@code ->} [index, letters[index]] } == [0:'a', 1:'b', 2:'c']
+ * assert (0..2).collectEntries( [4:'d'] ) { index {@code ->}
+ * [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
+ * </pre>
+ * Note: When using the list-style of result, the behavior is '<code>def (key, value) = listResultFromClosure</code>'.
+ * While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
+ * throwing away elements after the second one and using null for the key or value for the case of a shortened list.
+ * If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
*
- * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
- * containing items which match some criteria but leaving the original collection unchanged.
+ * @param self an Iterable
+ * @param collector the Map into which the transformed entries are put
+ * @param transform the closure used for transforming, which has an item from self as the parameter and
+ * should return a Map.Entry, a Map or a two-element list containing the resulting key and value
+ * @return the collector with all transformed values added to it
+ * @see #collectEntries(Iterator, Map, Closure)
+ * @since 1.8.7
+ */
+ public static <K, V, E> Map<K, V> collectEntries(Iterable<E> self, Map<K, V> collector, @ClosureParams(FirstParam.FirstGenericType.class) Closure<?> transform) {
+ return collectEntries(self.iterator(), collector, transform);
+ }
+
+ /**
+ * A variant of collectEntries for Iterators using the identity closure as the
+ * transform and a supplied map as the destination of transformed entries.
*
- * @param self a Collection to be modified
- * @param condition a closure condition
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see Iterator#remove()
- * @since 1.7.2
+ * @param self an Iterator
+ * @param collector the Map into which the transformed entries are put
+ * @return the collector with all transformed values added to it
+ * @see #collectEntries(Iterable, Map)
+ * @since 1.8.7
*/
- public static <T> boolean removeAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
- return self.removeIf(new BooleanClosurePredicate<>(condition));
+ public static <K, V> Map<K, V> collectEntries(Iterator<?> self, Map<K, V> collector) {
+ return collectEntries(self, collector, Closure.IDENTITY);
}
/**
- * Modifies this map by removing the elements that are matched according to the
- * specified closure condition. If the closure takes one parameter then it will be
- * passed the <code>Map.Entry</code>. Otherwise the closure should take two parameters, which
- * will be the key and the value.
- *
- * <pre class="groovyTestCase">def map = [a:1, b:2]
- * map.removeAll { k,v {@code ->} k == 'b' }
- * assert map == [a:1]</pre>
- *
- * See also <code>findAll</code> when wanting to produce a new map containing items
- * which match some criteria but leaving the original map unchanged.
+ * A variant of collectEntries for Iterables using the identity closure as the
+ * transform and a supplied map as the destination of transformed entries.
*
- * @param self a Map to be modified
- * @param condition a 1 or 2 arg Closure condition applying on the entries
- * @return <tt>true</tt> if this map changed as a result of the call
- * @since 2.5.0
+ * @param self an Iterable
+ * @param collector the Map into which the transformed entries are put
+ * @return the collector with all transformed values added to it
+ * @see #collectEntries(Iterator, Map)
+ * @since 1.8.7
*/
- public static <K, V> boolean removeAll(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure condition) {
- return self.entrySet().removeIf(new BooleanClosureForMapPredicate<>(condition));
+ public static <K, V> Map<K, V> collectEntries(Iterable<?> self, Map<K, V> collector) {
+ return collectEntries(self.iterator(), collector);
}
- /**
- * Modifies the collection by adding all the elements in the specified array to the collection.
- * The behavior of this operation is undefined if
- * the specified array is modified while the operation is in progress.
- *
- * See also <code>plus</code> or the '+' operator if wanting to produce a new collection
- * containing additional items but while leaving the original collection unchanged.
- *
- * @param self a Collection to be modified
- * @param items array containing elements to be added to this collection
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see Collection#addAll(Collection)
- * @since 1.7.2
- */
- public static <T> boolean addAll(Collection<T> self, T[] items) {
- return self.addAll(Arrays.asList(items));
+ @SuppressWarnings({"rawtypes","unchecked"})
+ private static <K, V> void addEntry(Map<K, V> result, Object newEntry) {
+ if (newEntry == null) {
+ // GROOVY-10893: insert nothing
+ } else if (newEntry instanceof Map) {
+ leftShift(result, (Map) newEntry);
+ } else if (newEntry instanceof List) {
+ var list = (List) newEntry;
+ // def (key, value) == list
+ Object key = list.isEmpty() ? null : list.get(0);
+ Object value = list.size() <= 1 ? null : list.get(1);
+ leftShift(result, new MapEntry(key, value));
+ } else if (newEntry.getClass().isArray()) {
+ Object[] array = (Object[]) newEntry;
+ // def (key, value) == array.toList()
+ Object key = array.length == 0 ? null : array[0];
+ Object value = array.length <= 1 ? null : array[1];
+ leftShift(result, new MapEntry(key, value));
+ } else {
+ // given Map.Entry is an interface, we get a proxy which gives us lots
+ // of flexibility but sometimes the error messages might be unexpected
+ leftShift(result, asType(newEntry, Map.Entry.class));
+ }
}
/**
- * Modifies this list by inserting all the elements in the specified array into the
- * list at the specified position. Shifts the
- * element currently at that position (if any) and any subsequent
- * elements to the right (increases their indices). The new elements
- * will appear in this list in the order that they occur in the array.
- * The behavior of this operation is undefined if the specified array
- * is modified while the operation is in progress.
+ * Finds the first value matching the closure condition.
*
- * See also <code>plus</code> for similar functionality with copy semantics, i.e. which produces a new
- * list after adding the additional items at the specified position but leaves the original list unchanged.
+ * <pre class="groovyTestCase">
+ * def numbers = [1, 2, 3]
+ * def result = numbers.find { it {@code >} 1}
+ * assert result == 2
+ * </pre>
*
- * @param self a list to be modified
- * @param items array containing elements to be added to this collection
- * @param index index at which to insert the first element from the
- * specified array
- * @return <tt>true</tt> if this collection changed as a result of the call
- * @see List#addAll(int, Collection)
- * @since 1.7.2
+ * @param self an Object with an iterator returning its values
+ * @param closure a closure condition
+ * @return the first Object found or null if none was found
+ * @since 1.0
*/
- public static <T> boolean addAll(List<T> self, int index, T[] items) {
- return self.addAll(index, Arrays.asList(items));
+ public static Object find(Object self, Closure closure) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
+ for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
+ Object value = iter.next();
+ if (bcw.call(value)) {
+ return value;
+ }
+ }
+ return null;
}
/**
- * Splits all items into two lists based on the closure condition.
- * The first list contains all items matching the closure expression.
- * The second list all those that don't.
+ * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).
+ * <p>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def items = [null, 0, 0.0, false, '', [], 42, 43]
+ * assert items.find() == 42
+ * </pre>
*
* @param self an Object with an Iterator returning its values
- * @param closure a closure condition
- * @return a List whose first item is the accepted values and whose second item is the rejected values
- * @since 1.6.0
+ * @return the first Object found or null if none was found
+ * @since 1.8.1
+ * @see Closure#IDENTITY
*/
- @SuppressWarnings("unchecked")
- public static Collection split(Object self, Closure closure) {
- List accept = new ArrayList();
- List reject = new ArrayList();
- return split(closure, accept, reject, InvokerHelper.asIterator(self));
+ public static Object find(Object self) {
+ return find(self, Closure.IDENTITY);
}
/**
- * Splits all items into two collections based on the closure condition.
- * The first list contains all items which match the closure expression.
- * The second list all those that don't.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }</pre>
+ * Finds the first value matching the closure condition. Example:
+ * <pre class="groovyTestCase">def list = [1,2,3]
+ * assert 2 == list.find { it {@code >} 1 }
+ * </pre>
*
- * @param self a Collection of values
+ * @param self a Collection
* @param closure a closure condition
- * @return a List whose first item is the accepted values and whose second item is the rejected values
- * @since 1.6.0
+ * @return the first Object found, in the order of the collections iterator, or null if no element matches
+ * @since 1.0
*/
- public static <T> Collection<Collection<T>> split(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- Collection<T> accept = createSimilarCollection(self);
- Collection<T> reject = createSimilarCollection(self);
- Iterator<T> iter = self.iterator();
- return split(closure, 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<>();
+ public static <T> T find(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
- while (iter.hasNext()) {
- T value = iter.next();
+ for (T value : self) {
if (bcw.call(value)) {
- accept.add(value);
- } else {
- reject.add(value);
+ return value;
}
}
- answer.add(accept);
- answer.add(reject);
- return answer;
+ return null;
}
/**
- * Splits all items into two collections based on the closure condition.
- * The first list contains all items which match the closure expression.
- * The second list all those that don't.
+ * Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).
* <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }</pre>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def items = [null, 0, 0.0, false, '', [], 42, 43]
+ * assert items.find() == 42
+ * </pre>
*
- * @param self a List of values
- * @param closure a closure condition
- * @return a List whose first item is the accepted values and whose second item is the rejected values
- * @since 2.4.0
+ * @param self a Collection
+ * @return the first Object found or null if none was found
+ * @since 1.8.1
+ * @see Closure#IDENTITY
*/
- @SuppressWarnings("unchecked")
- public static <T> List<List<T>> split(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (List<List<T>>) (List<?>) split((Collection<T>) self, closure);
+ public static <T> T find(Collection<T> self) {
+ return find(self, Closure.IDENTITY);
}
/**
- * Splits all items into two collections based on the closure condition.
- * The first list contains all items which match the closure expression.
- * The second list all those that don't.
+ * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns null.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [[2,4] as Set, [1,3] as Set] == ([1,2,3,4] as Set).split { it % 2 == 0 }</pre>
+ * <pre class="groovyTestCase">
+ * int[] numbers = [1, 2, 3]
+ * assert numbers.findResult { if(it {@code >} 1) return it } == 2
+ * assert numbers.findResult { if(it {@code >} 4) return it } == null
+ * </pre>
*
- * @param self a Set of values
- * @param closure a closure condition
- * @return a List whose first item is the accepted values and whose second item is the rejected values
- * @since 2.4.0
+ * @param self an Object with an iterator returning its values
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result of the closure
+ * @since 1.7.5
*/
- @SuppressWarnings("unchecked")
- public static <T> List<Set<T>> split(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
- return (List<Set<T>>) (List<?>) split((Collection<T>) self, closure);
+ public static Object findResult(Object self, Closure condition) {
+ for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); ) {
+ Object value = iter.next();
+ Object result = condition.call(value);
+ if (result != null) {
+ return result;
+ }
+ }
+ return null;
}
/**
- * Finds all combinations of items from the given aggregate of collections.
+ * Treats the object as iterable, iterating through the values it represents and returns the first non-null value, otherwise returns null.
* <p>
- * Example usage:
* <pre class="groovyTestCase">
- * result = [['a', 'b'], [1, 2, 3]].combinations()
- * assert result == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
+ * class Foo {
+ * List items
+ * Iterator iterator() {
+ * items.iterator()
+ * }
+ * }
+ * assert new Foo(items: [null, 2, 4]).findResult() == 2
+ * assert new Foo(items: [null, null]).findResult() == null
* </pre>
*
- * @param self an iterable of collections
- * @return A list of the combinations (lists).
- * @see GroovyCollections#combinations(Iterable)
- * @since 2.2.0
+ * @param self an Object with an iterator returning its values
+ * @return the first non-null result of the closure
+ * @since 4.0.9
*/
- public static List<List> combinations(Iterable self) {
- return GroovyCollections.combinations(self);
+ public static Object findResult(Object self) {
+ return findResult(self, Closure.IDENTITY);
}
/**
- * Finds all combinations of items from the given aggregate of collections,
- * then returns the results of the supplied transform.
+ * Treats the object as iterable, iterating through the values it represents and returns the first non-null result obtained from calling the closure, otherwise returns the defaultResult.
* <p>
- * Example usage:
* <pre class="groovyTestCase">
- * result = [[2, 3], [4, 5, 6]].combinations { x,y {@code ->} x*y }
- * assert result == [8, 12, 10, 15, 12, 18]
+ * int[] numbers = [1, 2, 3]
+ * assert numbers.findResult(5) { if(it {@code >} 1) return it } == 2
+ * assert numbers.findResult(5) { if(it {@code >} 4) return it } == 5
* </pre>
*
- * @param self an iterable of collections
- * @param function a closure to be called on each combination (list)
- * @return A list of the results of applying the closure to each combination.
- * @see GroovyCollections#combinations(Iterable)
- * @see #collect(Iterable,Closure)
- * @since 2.2.0
+ * @param self an Object with an iterator returning its values
+ * @param defaultResult an Object that should be returned if all closure results are null
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result of the closure, otherwise the default value
+ * @since 1.7.5
*/
- public static <T> List<T> combinations(Iterable self, @ClosureParams(value=FromString.class, options="List") Closure<T> function) {
- return collect(GroovyCollections.combinations(self), function);
+ public static Object findResult(Object self, Object defaultResult, Closure condition) {
+ Object result = findResult(self, condition);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Applies a function on each combination of the input lists.
+ * Treats the object as iterable, iterating through the values it represents and returns the first non-null result, otherwise returns the defaultResult.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">[[2, 3],[4, 5, 6]].eachCombination { println "Found $it" }</pre>
+ * <pre class="groovyTestCase">
+ * class Foo {
+ * List items
+ * Iterator iterator() {
+ * items.iterator()
+ * }
+ * }
+ * assert new Foo(items: [null, 2, 4]).findResult(5) == 2
+ * assert new Foo(items: [null, null]).findResult(5) == 5
+ * </pre>
*
- * @param self a Collection of lists
- * @param function a closure to be called on each combination
- * @see groovy.util.GroovyCollections#combinations(Iterable)
- * @since 2.2.0
+ * @param self an Object with an iterator returning its values
+ * @param defaultResult an Object that should be returned if all elements are null
+ * @return the first non-null element, otherwise the default value
+ * @since 4.0.9
*/
- @SuppressWarnings("unchecked")
- public static void eachCombination(Iterable self, Closure<?> function) {
- each(GroovyCollections.combinations(self), function);
+ public static Object findResult(Object self, Object defaultResult) {
+ Object result = findResult(self, Closure.IDENTITY);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Finds all non-null subsequences of a list.
+ * Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null
+ * result is found and returning that result. If all are null, the defaultResult is returned.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">def result = [1, 2, 3].subsequences()
- * assert result == [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] as Set</pre>
+ * Examples:
+ * <pre class="groovyTestCase">
+ * def iter = [1,2,3].iterator()
+ * assert "Found 2" == iter.findResult("default") { it {@code >} 1 ? "Found $it" : null }
+ * assert "default" == iter.findResult("default") { it {@code >} 3 ? "Found $it" : null }
+ * </pre>
*
- * @param self the List of items
- * @return the subsequences from the list
- * @since 1.7.0
+ * @param self an Iterator
+ * @param defaultResult an Object that should be returned if all closure results are null
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result from calling the closure, or the defaultValue
+ * @since 2.5.0
*/
- public static <T> Set<List<T>> subsequences(List<T> self) {
- return GroovyCollections.subsequences(self);
+ public static <S, T, U extends T, V extends T> T findResult(Iterator<S> self, U defaultResult, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> condition) {
+ T result = findResult(self, condition);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Finds all permutations of an iterable.
+ * Iterates through the Iterator stopping once the first non-null
+ * result is found and returning that result. If all are null, the defaultResult is returned.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">def result = [1, 2, 3].permutations()
- * assert result == [[3, 2, 1], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2, 1, 3], [1, 2, 3]] as Set</pre>
+ * Examples:
+ * <pre class="groovyTestCase">
+ * assert [null, 1, 2].iterator().findResult('default') == 1
+ * assert [null, null].findResult('default') == 'default'
+ * </pre>
*
- * @param self the Iterable of items
- * @return the permutations from the list
- * @since 1.7.0
+ * @param self an Iterator
+ * @param defaultResult an Object that should be returned if all elements are null
+ * @return the first non-null result from the iterator, or the defaultValue
+ * @since 4.0.9
*/
- public static <T> Set<List<T>> permutations(Iterable<T> self) {
- Set<List<T>> ans = new HashSet<>();
- PermutationGenerator<T> generator = new PermutationGenerator<>(self);
- while (generator.hasNext()) {
- ans.add(generator.next());
- }
- return ans;
+ public static <T, U extends T, V extends T> T findResult(Iterator<U> self, V defaultResult) {
+ T result = (T) findResult(self, Closure.IDENTITY);
+ return result == null ? defaultResult : result;
}
/**
- * Finds all permutations of an iterable, applies a function to each permutation and collects the result
- * into a list.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">Set result = [1, 2, 3].permutations { it.collect { v {@code ->} 2*v }}
- * assert result == [[6, 4, 2], [6, 2, 4], [2, 6, 4], [4, 6, 2], [4, 2, 6], [2, 4, 6]] as Set</pre>
+ * Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null
+ * result is found and returning that result. If all results are null, null is returned.
*
- * @param self the Iterable of items
- * @param function the function to apply on each permutation
- * @return the list of results of the application of the function on each permutation
- * @since 2.2.0
+ * @param self an Iterator
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result from calling the closure, or null
+ * @since 2.5.0
*/
- public static <T,V> List<V> permutations(Iterable<T> self, Closure<V> function) {
- return collect(permutations(self), function);
+ public static <T, U> T findResult(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
+ while (self.hasNext()) {
+ U next = self.next();
+ T result = condition.call(next);
+ if (result != null) {
+ return result;
+ }
+ }
+ return null;
}
/**
- * Iterates over all permutations of a collection, running a closure for each iteration.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">def permutations = []
- * [1, 2, 3].eachPermutation{ permutations << it }
- * assert permutations == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]</pre>
+ * Iterates through the Iterator stopping once the first non-null
+ * result is found and returning that result. If all results are null, null is returned.
*
- * @param self the Collection of items
- * @param closure the closure to call for each permutation
- * @return the permutations from the list
- * @since 1.7.0
+ * @param self an Iterator
+ * @return the first non-null result from the iterator, or null
+ * @since 4.0.9
*/
- public static <T> Iterator<List<T>> eachPermutation(Iterable<T> self, Closure closure) {
- Iterator<List<T>> generator = new PermutationGenerator<>(self);
- while (generator.hasNext()) {
- closure.call(generator.next());
- }
- return generator;
+ public static <T> T findResult(Iterator<T> self) {
+ return (T) findResult(self, Closure.IDENTITY);
}
/**
- * Adds GroovyCollections#transpose(List) as a method on lists.
- * A Transpose Function takes a collection of columns and returns a collection of
- * rows. The first row consists of the first element from each column. Successive
- * rows are constructed similarly.
+ * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
+ * result is found and returning that result. If all are null, the defaultResult is returned.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">
- * def result = [['a', 'b'], [1, 2]].transpose()
- * assert result == [['a', 1], ['b', 2]]
- * </pre>
+ * Examples:
* <pre class="groovyTestCase">
- * def result = [['a', 'b'], [1, 2], [3, 4]].transpose()
- * assert result == [['a', 1, 3], ['b', 2, 4]]
+ * def list = [1,2,3]
+ * assert "Found 2" == list.findResult("default") { it {@code >} 1 ? "Found $it" : null }
+ * assert "default" == list.findResult("default") { it {@code >} 3 ? "Found $it" : null }
* </pre>
*
- * @param self a List of lists
- * @return a List of the transposed lists
- * @see groovy.util.GroovyCollections#transpose(java.util.List)
- * @since 1.5.0
+ * @param self an Iterable
+ * @param defaultResult an Object that should be returned if all closure results are null
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result from calling the closure, or the defaultValue
+ * @since 2.5.0
*/
- public static List transpose(List self) {
- return GroovyCollections.transpose(self);
+ public static <S, T, U extends T, V extends T> T findResult(Iterable<S> self, U defaultResult, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> condition) {
+ T result = findResult(self, condition);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Sorts all Iterable members into groups determined by the supplied mapping closure.
- * The closure should return the key that this item should be grouped by. The returned
- * LinkedHashMap will have an entry for each distinct key returned from the closure,
- * with each value being a list of items for that group.
+ * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
+ * result is found and returning that result. If all are null, the defaultResult is returned.
* <p>
- * Example usage:
+ * Examples:
* <pre class="groovyTestCase">
- * assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }
+ * assert [null, 1, 2].findResult('default') == 1
+ * assert [null, null].findResult('default') == 'default'
* </pre>
*
- * @param self a collection to group
- * @param closure a closure mapping entries on keys
- * @return a new Map grouped by keys
- * @since 2.2.0
+ * @param self an Iterable
+ * @param defaultResult an Object that should be returned if all elements in the iterable are null
+ * @return the first non-null element from the iterable, or the defaultValue
+ * @since 4.0.9
*/
- public static <K, T> Map<K, List<T>> groupBy(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
- Map<K, List<T>> answer = new LinkedHashMap<>();
- for (T element : self) {
- K value = closure.call(element);
- groupAnswer(answer, element, value);
- }
- return answer;
+ public static <T, U extends T, V extends T> T findResult(Iterable<U> self, V defaultResult) {
+ T result = (T) findResult(self, Closure.IDENTITY);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Sorts all Iterable members into (sub)groups determined by the supplied
- * mapping closures. Each closure should return the key that this item
- * should be grouped by. The returned LinkedHashMap will have an entry for each
- * distinct 'key path' returned from the closures, with each value being a list
- * of items for that 'group path'.
- *
- * Example usage:
- * <pre class="groovyTestCase">def result = [1,2,3,4,5,6].groupBy({ it % 2 }, { it {@code <} 4 })
- * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]</pre>
- *
- * Another example:
- * <pre>def sql = groovy.sql.Sql.newInstance(/* ... */)
- * def data = sql.rows("SELECT * FROM a_table").groupBy({ it.column1 }, { it.column2 }, { it.column3 })
- * if (data.val1.val2.val3) {
- * // there exists a record where:
- * // a_table.column1 == val1
- * // a_table.column2 == val2, and
- * // a_table.column3 == val3
- * } else {
- * // there is no such record
- * }</pre>
- * If an empty array of closures is supplied the IDENTITY Closure will be used.
+ * Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
+ * result is found and returning that result. If all results are null, null is returned.
*
- * @param self a collection to group
- * @param closures an array of closures, each mapping entries on keys
- * @return a new Map grouped by keys on each criterion
- * @since 2.2.0
- * @see Closure#IDENTITY
+ * @param self an Iterable
+ * @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
+ * @return the first non-null result from calling the closure, or null
+ * @since 2.5.0
*/
- public static Map groupBy(Iterable self, Object... closures) {
- final Closure head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0];
-
- @SuppressWarnings("unchecked")
- Map<Object, List> first = groupBy(self, head);
- if (closures.length < 2)
- return first;
-
- final Object[] tail = new Object[closures.length - 1];
- System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6
-
- // inject([:]) { a,e {@code ->} a {@code <<} [(e.key): e.value.groupBy(tail)] }
- Map<Object, Map> acc = new LinkedHashMap<>();
- for (Map.Entry<Object, List> item : first.entrySet()) {
- acc.put(item.getKey(), groupBy(item.getValue(), tail));
- }
-
- return acc;
+ public static <T, U> T findResult(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
+ return findResult(self.iterator(), condition);
}
/**
- * Sorts all Iterable members into (sub)groups determined by the supplied
- * mapping closures. Each closure should return the key that this item
- * should be grouped by. The returned LinkedHashMap will have an entry for each
- * distinct 'key path' returned from the closures, with each value being a list
- * of items for that 'group path'.
+ * Iterates through the Iterable stopping once the first non-null
+ * result is found and returning that result. If all results are null, null is returned.
*
- * Example usage:
+ * @param self an Iterable
+ * @return the first non-null element from the iterable, or null
+ * @since 4.0.9
+ */
+ public static <T> T findResult(Iterable<T> self) {
+ return (T) findResult(self.iterator(), Closure.IDENTITY);
+ }
+
+ /**
+ * Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned.
+ * If the closure takes two parameters, the entry key and value are passed.
+ * If the closure takes one parameter, the Map.Entry object is passed.
* <pre class="groovyTestCase">
- * def result = [1,2,3,4,5,6].groupBy([{ it % 2 }, { it {@code <} 4 }])
- * assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]
+ * assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
+ * assert null == [a:1, b:3].findResult { if (it.value == 9) return "Found ${it.key}:${it.value}" }
+ * assert "Found a:1" == [a:1, b:3].findResult { k, v {@code ->} if (k.size() + v == 2) return "Found $k:$v" }
* </pre>
*
- * Another example:
- * <pre>
- * def sql = groovy.sql.Sql.newInstance(/* ... */)
- * def data = sql.rows("SELECT * FROM a_table").groupBy([{ it.column1 }, { it.column2 }, { it.column3 }])
- * if (data.val1.val2.val3) {
- * // there exists a record where:
- * // a_table.column1 == val1
- * // a_table.column2 == val2, and
- * // a_table.column3 == val3
- * } else {
- * // there is no such record
- * }
+ * @param self a Map
+ * @param condition a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
+ * @return the first non-null result collected by calling the closure, or null if no such result was found
+ * @since 1.7.5
+ */
+ public static <T, K, V> T findResult(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> condition) {
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ T result = callClosureForMapEntry(condition, entry);
+ if (result != null) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned.
+ * If the closure takes two parameters, the entry key and value are passed.
+ * If the closure takes one parameter, the Map.Entry object is passed.
+ * <pre class="groovyTestCase">
+ * assert "Found b:3" == [a:1, b:3].findResult("default") { if (it.value == 3) return "Found ${it.key}:${it.value}" }
+ * assert "default" == [a:1, b:3].findResult("default") { if (it.value == 9) return "Found ${it.key}:${it.value}" }
+ * assert "Found a:1" == [a:1, b:3].findResult("default") { k, v {@code ->} if (k.size() + v == 2) return "Found $k:$v" }
* </pre>
- * If an empty list of closures is supplied the IDENTITY Closure will be used.
*
- * @param self a collection to group
- * @param closures a list of closures, each mapping entries on keys
- * @return a new Map grouped by keys on each criterion
- * @since 2.2.0
- * @see Closure#IDENTITY
+ * @param self a Map
+ * @param defaultResult an Object that should be returned if all closure results are null
+ * @param condition a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned
+ * @return the first non-null result collected by calling the closure, or the defaultResult if no such result was found
+ * @since 1.7.5
*/
- public static Map groupBy(Iterable self, List<Closure> closures) {
- return groupBy(self, closures.toArray());
+ public static <T, U extends T, V extends T, A, B> T findResult(Map<A, B> self, U defaultResult, @ClosureParams(MapEntryOrKeyValue.class) Closure<V> condition) {
+ T result = findResult(self, condition);
+ if (result == null) return defaultResult;
+ return result;
}
/**
- * Sorts all collection members into groups determined by the supplied mapping
- * closure and counts the group size. The closure should return the key that each
- * item should be grouped by. The returned Map will have an entry for each
- * distinct key returned from the closure, with each value being the frequency of
- * items occurring for that group.
+ * Iterates through the Iterable transforming items using the supplied closure
+ * and collecting any non-null results.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }</pre>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def list = [1,2,3]
+ * def result = list.findResults { it {@code >} 1 ? "Found $it" : null }
+ * assert result == ["Found 2", "Found 3"]
+ * </pre>
*
- * @param self a collection to group and count
- * @param closure a closure mapping items to the frequency keys
- * @return a new Map grouped by keys with frequency counts
+ * @param self an Iterable
+ * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded
+ * @return the list of non-null transformed values
* @since 2.2.0
*/
- public static <K,E> Map<K, Integer> countBy(Iterable<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
- return countBy(self.iterator(), closure);
+ public static <T, U> Collection<T> findResults(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
+ return findResults(self.iterator(), filteringTransform);
}
/**
- * Sorts all iterator items into groups determined by the supplied mapping
- * closure and counts the group size. The closure should return the key that each
- * item should be grouped by. The returned Map will have an entry for each
- * distinct key returned from the closure, with each value being the frequency of
- * items occurring for that group.
+ * Iterates through the Iterable collecting any non-null results.
* <p>
- * Example usage:
- * <pre class="groovyTestCase">assert [1,2,2,2,3].toSet().iterator().countBy{ it % 2 } == [1:2, 0:1]</pre>
+ * Example:
+ * <pre class="groovyTestCase">
+ * assert [1, null, 2, null, 3].findResults() == [1, 2, 3]
+ * </pre>
*
- * @param self an iterator to group and count
- * @param closure a closure mapping items to the frequency keys
- * @return a new Map grouped by keys with frequency counts
- * @since 1.8.0
+ * @param self an Iterable
+ * @return the list of non-null values
+ * @since 4.0.9
*/
- public static <K,E> Map<K, Integer> countBy(Iterator<E> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<K> closure) {
- Map<K, Integer> answer = new LinkedHashMap<>();
- while (self.hasNext()) {
- K value = closure.call(self.next());
- countAnswer(answer, value);
- }
- return answer;
+ public static <T> Collection<T> findResults(Iterable<T> self) {
+ return findResults(self.iterator(), Closure.IDENTITY);
}
/**
- * Groups all map entries into groups determined by the
- * supplied mapping closure. The closure will be passed a Map.Entry or
- * key and value (depending on the number of parameters the closure accepts)
- * and should return the key that each item should be grouped under. The
- * resulting map will have an entry for each 'group' key returned by the
- * closure, with values being the list of map entries that belong to each
- * group. (If instead of a list of map entries, you want an actual map
- * use {code}groupBy{code}.)
- * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupEntriesBy { it.value % 2 }
- * assert result[0]*.key == ["b", "d", "f"]
- * assert result[1]*.value == [1, 3, 5]</pre>
+ * Iterates through the Iterator transforming items using the supplied closure
+ * and collecting any non-null results.
*
- * @param self a map to group
- * @param closure a 1 or 2 arg Closure mapping entries on keys
- * @return a new Map grouped by keys
- * @since 1.5.2
+ * @param self an Iterator
+ * @param filteringTransform a Closure that should return either a non-null transformed value or null for items which should be discarded
+ * @return the list of non-null transformed values
+ * @since 2.5.0
*/
- public static <G, K, V> Map<G, List<Map.Entry<K, V>>> groupEntriesBy(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<G> closure) {
- final Map<G, List<Map.Entry<K, V>>> answer = new LinkedHashMap<>();
- for (Map.Entry<K, V> entry : self.entrySet()) {
- G value = callClosureForMapEntry(closure, entry);
- groupAnswer(answer, entry, value);
+ public static <T, U> Collection<T> findResults(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> filteringTransform) {
+ List<T> result = new ArrayList<>();
+ while (self.hasNext()) {
+ U value = self.next();
+ T transformed = filteringTransform.call(value);
+ if (transformed != null) {
+ result.add(transformed);
+ }
}
- return answer;
+ return result;
}
/**
- * Groups the members of a map into sub maps determined by the
- * supplied mapping closure. The closure will be passed a Map.Entry or
- * key and value (depending on the number of parameters the closure accepts)
- * and should return the key that each item should be grouped under. The
- * resulting map will have an entry for each 'group' key returned by the
- * closure, with values being the map members from the original map that
- * belong to each group. (If instead of a map, you want a list of map entries
- * use {code}groupEntriesBy{code}.)
- * <p>
- * If the <code>self</code> map is one of TreeMap, Hashtable or Properties,
- * the returned Map will preserve that type, otherwise a LinkedHashMap will
- * be returned.
- * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy { it.value % 2 }
- * assert result == [0:[b:2, d:4, f:6], 1:[a:1, c:3, e:5]]</pre>
+ * Iterates through the Iterator collecting any non-null results.
*
- * @param self a map to group
- * @param closure a closure mapping entries on keys
- * @return a new Map grouped by keys
- * @since 1.0
+ * @param self an Iterator
+ * @return the list of non-null values
+ * @since 4.0.9
*/
- public static <G, K, V> Map<G, Map<K, V>> groupBy(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<G> closure) {
- final Map<G, List<Map.Entry<K, V>>> initial = groupEntriesBy(self, closure);
- final Map<G, Map<K, V>> answer = new LinkedHashMap<>();
- for (Map.Entry<G, List<Map.Entry<K, V>>> outer : initial.entrySet()) {
- G key = outer.getKey();
- List<Map.Entry<K, V>> entries = outer.getValue();
- Map<K, V> target = createSimilarMap(self);
- putAll(target, entries);
- answer.put(key, target);
- }
- return answer;
+ public static <T> Collection<T> findResults(Iterator<T> self) {
+ return findResults(self, Closure.IDENTITY);
}
/**
- * 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
- * value (depending on the number of parameters the closure accepts) and
- * should return the key that each item should be grouped under. The
- * resulting map will have an entry for each 'group path' returned by all
- * closures, with values being the map members from the original map that
- * belong to each such 'group path'.
- *
- * If the <code>self</code> map is one of TreeMap, Hashtable, or Properties,
- * the returned Map will preserve that type, otherwise a LinkedHashMap will
- * be returned.
- *
- * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy({ it.value % 2 }, { it.key.next() })
- * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre>
- * If an empty array of closures is supplied the IDENTITY Closure will be used.
+ * Iterates through the map transforming items using the supplied closure
+ * and collecting any non-null results.
+ * If the closure takes two parameters, the entry key and value are passed.
+ * If the closure takes one parameter, the Map.Entry object is passed.
+ * <p>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def map = [a:1, b:2, hi:2, cat:3, dog:2]
+ * def result = map.findResults { k, v {@code ->} k.size() == v ? "Found $k:$v" : null }
+ * assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
+ * </pre>
*
- * @param self a map to group
- * @param closures an array of closures that map entries on keys
- * @return a new map grouped by keys on each criterion
+ * @param self a Map
+ * @param filteringTransform a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discarded
+ * @return the list of non-null transformed values
* @since 1.8.1
- * @see Closure#IDENTITY
*/
- public static Map<Object, Map> groupBy(Map self, Object... closures) {
- @SuppressWarnings("unchecked")
- final Closure<Object> head = closures.length == 0 ? Closure.IDENTITY : (Closure) closures[0];
-
- @SuppressWarnings("unchecked")
- Map<Object, Map> first = groupBy(self, head);
- if (closures.length < 2)
- return first;
-
- final Object[] tail = new Object[closures.length - 1];
- System.arraycopy(closures, 1, tail, 0, closures.length - 1); // Arrays.copyOfRange only since JDK 1.6
-
- Map<Object, Map> acc = new LinkedHashMap<>();
- for (Map.Entry<Object, Map> item: first.entrySet()) {
- acc.put(item.getKey(), groupBy(item.getValue(), tail));
+ public static <T, K, V> Collection<T> findResults(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> filteringTransform) {
+ List<T> result = new ArrayList<>();
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ T transformed = callClosureForMapEntry(filteringTransform, entry);
+ if (transformed != null) {
+ result.add(transformed);
+ }
}
-
- return acc;
+ return result;
}
/**
- * 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
- * value (depending on the number of parameters the closure accepts) and
- * should return the key that each item should be grouped under. The
- * resulting map will have an entry for each 'group path' returned by all
- * closures, with values being the map members from the original map that
- * belong to each such 'group path'.
- *
- * If the <code>self</code> map is one of TreeMap, Hashtable, or Properties,
- * the returned Map will preserve that type, otherwise a LinkedHashMap will
- * be returned.
- *
- * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }])
- * assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]</pre>
- * If an empty list of closures is supplied the IDENTITY Closure will be used.
+ * Finds the first entry matching the closure condition.
+ * If the closure takes two parameters, the entry key and value are passed.
+ * If the closure takes one parameter, the Map.Entry object is passed.
+ * <pre class="groovyTestCase">assert [a:1, b:3].find { it.value == 3 }.key == "b"</pre>
*
- * @param self a map to group
- * @param closures a list of closures that map entries on keys
- * @return a new map grouped by keys on each criterion
- * @since 1.8.1
- * @see Closure#IDENTITY
+ * @param self a Map
+ * @param closure a 1 or 2 arg Closure condition
+ * @return the first Object found
+ * @since 1.0
*/
- public static Map<Object, Map> groupBy(Map self, List<Closure> closures) {
- return groupBy(self, closures.toArray());
+ public static <K, V> Map.Entry<K, V> find(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> closure) {
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (bcw.callForMap(entry)) {
+ return entry;
+ }
+ }
+ return null;
}
/**
- * Groups the members of a map into groups determined by the
- * supplied mapping closure and counts the frequency of the created groups.
- * The closure will be passed a Map.Entry or
- * key and value (depending on the number of parameters the closure accepts)
- * and should return the key that each item should be grouped under. The
- * resulting map will have an entry for each 'group' key returned by the
- * closure, with values being the frequency counts for that 'group'.
+ * Finds all entries matching the closure condition. If the
+ * closure takes one parameter then it will be passed the Map.Entry.
+ * Otherwise if the closure should take two parameters, which will be
+ * the key and the value.
* <p>
- * <pre class="groovyTestCase">def result = [a:1,b:2,c:3,d:4,e:5].countBy { it.value % 2 }
- * assert result == [0:2, 1:3]</pre>
+ * If the <code>self</code> map is one of TreeMap, LinkedHashMap, Hashtable
+ * or Properties, the returned Map will preserve that type, otherwise a HashMap will
+ * be returned.
+ * <p>
+ * Example usage:
+ * <pre class="groovyTestCase">
+ * def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
+ * assert result.every { it instanceof Map.Entry }
+ * assert result*.key == ["b", "c"]
+ * assert result*.value == [2, 4]
+ * </pre>
*
- * @param self a map to group and count
- * @param closure a closure mapping entries to frequency count keys
- * @return a new Map grouped by keys with frequency counts
- * @since 1.8.0
+ * @param self a Map
+ * @param closure a 1 or 2 arg Closure condition applying on the entries
+ * @return a new subMap
+ * @since 1.0
*/
- public static <K,U,V> Map<K, Integer> countBy(Map<U,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<K> closure) {
- Map<K, Integer> answer = new LinkedHashMap<>();
- for (Map.Entry<U,V> entry : self.entrySet()) {
- countAnswer(answer, callClosureForMapEntry(closure, entry));
+ public static <K, V> Map<K, V> findAll(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure closure) {
+ Map<K, V> answer = createSimilarMap(self);
+ BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
+ for (Map.Entry<K, V> entry : self.entrySet()) {
+ if (bcw.callForMap(entry)) {
+ answer.put(entry.getKey(), entry.getValue());
+ }
}
return answer;
}
/**
- * Groups the current element according to the value
+ * Finds all values matching the closure condition.
+ * <pre class="groovyTestCase">assert ([2,4] as Set) == ([1,2,3,4] as Set).findAll { it % 2 == 0 }</pre>
*
- * @param answer the map containing the results
- * @param element the element to be placed
- * @param value the value according to which the element will be placed
- * @since 1.5.0
+ * @param self a Set
+ * @param closure a closure condition
+ * @return a Set of matching values
+ * @since 2.4.0
*/
- protected static <K, T> void groupAnswer(final Map<K, List<T>> answer, T element, K value) {
- List<T> groupedElements = answer.computeIfAbsent(value, k -> new ArrayList<>());
-
- groupedElements.add(element);
- }
-
- private static <T> void countAnswer(final Map<T, Integer> answer, T mappedKey) {
- Integer current = answer.get(mappedKey);
-
- if (null == current) {
- current = 0;
- }
-
- answer.put(mappedKey, current + 1);
+ public static <T> Set<T> findAll(Set<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (Set<T>) findAll((Collection<T>) self, closure);
}
- // internal helper method
- protected static <T, K, V> T callClosureForMapEntry(@ClosureParams(value=FromString.class, options={"K,V","Map.Entry<K,V>"}) Closure<T> closure, Map.Entry<K,V> entry) {
- if (closure.getMaximumNumberOfParameters() == 2) {
- return closure.call(entry.getKey(), entry.getValue());
- }
- return closure.call(entry);
+ /**
+ * Finds all values matching the closure condition.
+ * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
+ *
+ * @param self a List
+ * @param closure a closure condition
+ * @return a List of matching values
+ * @since 2.4.0
+ */
+ public static <T> List<T> findAll(List<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return (List<T>) findAll((Collection<T>) self, closure);
}
- // internal helper method
- protected static <T> T callClosureForLine(@ClosureParams(value=FromString.class, options={"String","String,Integer"}) Closure<T> closure, String line, int counter) {
- if (closure.getMaximumNumberOfParameters() == 2) {
- return closure.call(line, counter);
- }
- return closure.call(line);
+ /**
+ * Finds all values matching the closure condition.
+ * <pre class="groovyTestCase">assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }</pre>
+ *
+ * @param self a Collection
+ * @param closure a closure condition
+ * @return a Collection of matching values
+ * @since 1.5.6
+ */
+ public static <T> Collection<T> findAll(Collection<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) {
+ return findMany(createSimilarCollection(self), self.iterator(), closure);
}
- // internal helper method
- protected static <T, K, V> T callClosureForMapEntryAndCounter(@ClosureParams(value=FromString.class, options={"K,V,Integer", "K,V","Map.Entry<K,V>"}) Closure<T> closure, Map.Entry<K,V> entry, int counter) {
- if (closure.getMaximumNumberOfParameters() == 3) {
- return closure.call(entry.getKey(), entry.getValue(), counter);
- }
- if (closure.getMaximumNumberOfParameters() == 2) {
- return closure.call(entry, counter);
- }
- return closure.call(entry);
+ /**
+ * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
+ * <p>
+ * Example:
+ * <pre class="groovyTestCase">
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set
+ * assert items.findAll() == [1, 2, true, 'foo', [4, 5]] as Set
+ * </pre>
+ *
+ * @param self a Set
+ * @return a Set of the truthy values
+ * @since 2.4.0
+ * @see Closure#IDENTITY
+ */
+ public static <T> Set<T> findAll(Set<T> self) {
+ return findAll(self, Closure.IDENTITY);
}
/**
- * Performs the same function as the version of inject that takes an initial value, but
- * uses the head of the Collection as the initial value, and iterates over the tail.
+ * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
+ * <p>
+ * Example:
* <pre class="groovyTestCase">
- * assert 1 * 2 * 3 * 4 == [ 1, 2, 3, 4 ].inject { acc, val {@code ->} acc * val }
- * assert ['b'] == [['a','b'], ['b','c'], ['d','b']].inject { acc, val {@code ->} acc.intersect( val ) }
- * LinkedHashSet set = [ 't', 'i', 'm' ]
- * assert 'tim' == set.inject { a, b {@code ->} a + b }
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
* </pre>
*
- * @param self a Collection
- * @param closure a closure
- * @return the result of the last closure call
- * @throws NoSuchElementException if the collection is empty.
- * @see #inject(Collection, Object, Closure)
- * @since 1.8.7
+ * @param self a List
+ * @return a List of the truthy values
+ * @since 2.4.0
+ * @see Closure#IDENTITY
*/
- @SuppressWarnings("unchecked")
- public static <T, V extends T> T inject(Collection<T> self, @ClosureParams(value=FromString.class,options="V,T") Closure<V> closure ) {
- if( self.isEmpty() ) {
- throw new NoSuchElementException( "Cannot call inject() on an empty collection without passing an initial value." ) ;
- }
- Iterator<T> iter = self.iterator();
- T head = iter.next();
- Collection<T> tail = tail(self);
- if (!tail.iterator().hasNext()) {
- return head;
- }
- // cast with explicit weaker generics for now to keep jdk6 happy, TODO: find better fix
- return (T) inject((Collection) tail, head, closure);
+ public static <T> List<T> findAll(List<T> self) {
+ return findAll(self, Closure.IDENTITY);
}
/**
- * Iterates through the given Collection, passing in the initial value to
- * the 2-arg closure along with the first item. The result is passed back (injected) into
- * the closure along with the second item. The new result is injected back into
- * the closure along with the third item and so on until the entire collection
- * has been used. Also known as <tt>foldLeft</tt> or <tt>reduce</tt> in functional parlance.
- *
- * Examples:
+ * Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
+ * <p>
+ * Example:
* <pre class="groovyTestCase">
- * assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val {@code ->} acc * val }
- *
- * assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val {@code ->} acc + val }
- *
- * assert 'The quick brown fox' ==
- * ['quick', 'brown', 'fox'].inject('The') { acc, val {@code ->} acc + ' ' + val }
- *
- * assert 'bat' ==
- * ['rat', 'bat', 'cat'].inject('zzz') { min, next {@code ->} next {@code <} min ? next : min }
- *
- * def max = { a, b {@code ->} [a, b].max() }
- * def animals = ['bat', 'rat', 'cat']
- * assert 'rat' == animals.inject('aaa', max)
- * </pre>
- * Visual representation of the last example above:
- * <pre>
- * initVal animals[0]
- * v v
- * max('aaa', 'bat') {@code =>} 'bat' animals[1]
- * v v
- * max('bat', 'rat') {@code =>} 'rat' animals[2]
- * v v
- * max('rat', 'cat') {@code =>} 'rat'
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
* </pre>
*
- * @param self a Collection
- * @param initialValue some initial value
- * @param closure a closure
- * @return the result of the last closure call
- * @since 1.0
+ * @param self a Collection
+ * @return a Collection of the truthy values
+ * @since 1.8.1
+ * @see Closure#IDENTITY
+ */
+ public static <T> Collection<T> findAll(Collection<T> self) {
+ return findAll(self, Closure.IDENTITY);
+ }
+
+ /**
+ * Finds all items matching the closure condition.
+ *
+ * @param self an Object with an Iterator returning its values
+ * @param closure a closure condition
+ * @return a List of the values found
+ * @since 1.6.0
*/
@SuppressWarnings("unchecked")
- public static <E, T, U extends T, V extends T> T inject(Collection<E> self, U initialValue, @ClosureParams(value=FromString.class,options="U,E") Closure<V> closure) {
- // cast with explicit weaker generics for now to keep jdk6 happy, TODO: find better fix
- return (T) inject((Iterator) self.iterator(), initialValue, closure);
+ public static List findAll(Object self, Closure closure) {
+ return findMany(new ArrayList(), InvokerHelper.asIterator(self), closure);
}
/**
- * Iterates through the given Map, passing in the initial value to
- * the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value).
- * The result is passed back (injected) into
- * the closure along with the second item. The new result is injected back into
- * the closure along with the third item and so on until the entire collection
- * has been used. Also known as <tt>foldLeft</tt> or <tt>reduce</tt> in functional parlance.
- *
- * Examples:
+ * Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth).
+ * <p>
+ * Example:
* <pre class="groovyTestCase">
- * def map = [a:1, b:2, c:3]
- * assert map.inject([]) { list, k, v {@code ->}
- * list + [k] * v
- * } == ['a', 'b', 'b', 'c', 'c', 'c']
+ * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
+ * assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
* </pre>
*
- * @param self a Map
- * @param initialValue some initial value
- * @param closure a 2 or 3 arg Closure
- * @return the result of the last closure call
+ * @param self an Object with an Iterator returning its values
+ * @return a List of the truthy values
* @since 1.8.1
+ * @see Closure#IDENTITY
*/
- public static <K, V, T, U extends T, W extends T> T inject(Map<K, V> self, U initialValue, @ClosureParams(value=FromString.class,options={"U,Map.Entry<K,V>","U,K,V"}) Closure<W> closure) {
- T value = initialValue;
- for (Map.Entry<K, V> entry : self.entrySet()) {
- if (closure.getMaximumNumberOfParameters() == 3) {
- value = closure.call(value, entry.getKey(), entry.getValue());
- } else {
- value = closure.call(value, entry);
+ public static List findAll(Object self) {
+ return findAll(self, Closure.IDENTITY);
+ }
+
+ static <T, C extends Collection<T>> C findMany(C collector, Iterator<? extends T> iter, Closure<?> closure) {
+ BooleanClosureWrapper test = new BooleanClosureWrapper(closure);
+ while (iter.hasNext()) {
+ T value = iter.next();
+ if (test.call(value)) {
+ collector.add(value);
}
}
- return value;
+ return collector;
}
/**
- * Iterates through the given Iterator, passing in the initial value to
- * the closure along with the first item. The result is passed back (injected) into
- * the closure along with the second item. The new result is injected back into
- * the closure along with the third item and so on until the Iterator has been
- * expired of values. Also known as foldLeft in functional parlance.
+ * Returns <tt>true</tt> if this iterable contains the item.
*
- * @param self an Iterator
- * @param initialValue some initial value
- * @param closure a closure
- * @return the result of the last closure call
- * @see #inject(Collection, Object, Closure)
- * @since 1.5.0
+ * @param self an Iterable to be checked for containment
+ * @param item an Object to be checked for containment in this iterable
+ * @return <tt>true</tt> if this iterable contains the item
+ * @see Collection#contains(Object)
+ * @since 2.4.0
*/
- public static <E,T, U extends T, V extends T> T inject(Iterator<E> self, U initialValue, @ClosureParams(value=FromString.class,options="U,E") Closure<V> closure) {
- T value = initialValue;
- Object[] params = new Object[2];
- while (self.hasNext()) {
- Object item = self.next();
- params[0] = value;
- params[1] = item;
- value = closure.call(params);
+ public static boolean contains(Iterable self, Object item) {
+ for (Object e : self) {
+ if (Objects.equals(item, e)) {
+ return true;
+ }
}
- return value;
+ return false;
}
/**
- * Iterates through the given Object, passing in the first value to
- * the closure along with the first item. The result is passed back (injected) into
- * the closure along with the second item. The new result is injected back into
- * the closure along with the third item and so on until further iteration of
- * the object is not possible. Also known as foldLeft in functional parlance.
+ * Returns <tt>true</tt> if this iterable contains all the elements
+ * in the specified array.
*
- * @param self an Object
- * @param closure a closure
- * @return the result of the last closure call
- * @throws NoSuchElementException if the collection is empty.
- * @see #inject(Collection, Object, Closure)
- * @since 1.8.7
+ * @param self an Iterable to be checked for containment
+ * @param items array to be checked for containment in this iterable
+ * @return <tt>true</tt> if this collection contains all the elements
+ * in the specified array
+ * @see Collection#containsAll(Collection)
+ * @since 2.4.0
*/
- @SuppressWarnings("unchecked")
- public static <T, V extends T> T inject(Object self, Closure<V> closure) {
- Iterator iter = InvokerHelper.asIterator(self);
- if( !iter.hasNext() ) {
- throw new NoSuchElementException( "Cannot call inject() over an empty iterable without passing an initial value." ) ;
- }
- Object initialValue = iter.next() ;
- return (T) inject(iter, initialValue, closure);
+ public static boolean containsAll(Iterable<?> self, Object[] items) {
+ return asCollection(self).containsAll(Arrays.asList(items));
}
/**
- * Iterates through the given Object, passing in the initial value to
- * the closure along with the first item. The result is passed back (injected) into
- * the closure along with the second item. The new result is injected back into
- * the closure along with the third item and so on until further iteration of
- * the object is not possible. Also known as foldLeft in functional parlance.
+ * Modifies this collection by removing its elements that are contained
+ * within the specified object array.
*
- * @param self an Object
- * @param initialValue some initial value
- * @param closure a closure
- * @return the result of the last closure call
- * @see #inject(Collection, Object, Closure)
- * @since 1.5.0
+ * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
+ * containing items which don't match some criteria while leaving the original collection unchanged.
+ *
+ * @param self a Collection to be modified
+ * @param items array containing elements to be removed from this collection
+ * @return <tt>true</tt> if this collection changed as a result of the call
+ * @see Collection#removeAll(Collection)
+ * @since 1.7.2
*/
@SuppressWarnings("unchecked")
- public static <T, U extends T, V extends T> T inject(Object self, U initialValue, Closure<V> closure) {
- Iterator iter = InvokerHelper.asIterator(self);
- return (T) inject(iter, initialValue, closure);
+ public static boolean removeAll(Collection self, Object[] items) {
+ Collection pickFrom = new TreeSet(new NumberAwareComparator());
+ pickFrom.addAll(Arrays.asList(items));
+ return self.removeAll(pickFrom);
}
/**
- * Sums the items in an Iterable. This is equivalent to invoking the
- * "plus" method on all items in the Iterable.
- * <pre class="groovyTestCase">assert 1+2+3+4 == [1,2,3,4].sum()</pre>
+ * Modifies this collection so that it retains only its elements that are contained
+ * in the specified array. In other words, removes from this collection all of
+ * its elements that are not contained in the specified array.
*
- * @param self Iterable of values to add together
- * @return The sum of all the items
- * @see #sum(Iterator)
- * @since 2.2.0
- */
- public static Object sum(Iterable<?> self) {
- return sum(self.iterator(), null, true);
- }
-
- /**
- * Sums the items from an Iterator. This is equivalent to invoking the
- * "plus" method on all items from the Iterator. The iterator will become
- * exhausted of elements after determining the sum value.
+ * See also <code>grep</code> and <code>findAll</code> when wanting to produce a new list
+ * containing items which match some specified items but leaving the original collection unchanged.
*
- * @param self an Iterator for the values to add together
- * @return The sum of all the items
- * @since 1.5.5
+ * @param self a Collection to be modified
+ * @param items array containing elements to be retained from this collection
+ * @return <tt>true</tt> if this collection changed as a result of the call
+ * @see Collection#retainAll(Collection)
+ * @since 1.7.2
*/
- public static Object sum(Iterator<Object> self) {
- return sum(self, null, true);
+ @SuppressWarnings("unchecked")
+ public static boolean retainAll(Collection self, Object[] items) {
+ Collection pickFrom = new TreeSet(new NumberAwareComparator());
+ pickFrom.addAll(Arrays.asList(items));
+ return self.retainAll(pickFrom);
}
/**
- * Sums the items in an Iterable, adding the result to some initial value.
- * <pre class="groovyTestCase">
- * assert 5+1+2+3+4 == [1,2,3,4].sum(5)
- * </pre>
+ * Modifies this collection so that it retains only its elements
+ * that are matched according to the specified closure condition. In other words,
+ * removes from this collection all of its elements that don't match.
*
- * @param self an Iterable of values to sum
- * @param initialValue the items in the collection will be summed to this initial value
- * @return The sum of all the items.
- * @see #sum(Iterator, Object)
- * @since 2.2.0
+ * <pre class="groovyTestCase">def list = ['a', 'b']
+ * list.retainAll { it == 'b' }
+ * assert list == ['b']</pre>
+ *
+ * See also <code>findAll</code> and <code>grep</code> when wanting to produce a new list
+ * containing items which match some criteria but leaving the original collection unchanged.
+ *
+ * @param self a Collection to be modified
+ * @param condition a closure condition
+ * @return <tt>true</tt> if this collection changed as a result of the call
+ * @see Iterator#remove()
+ * @since 1.7.2
*/
- public static Object sum(Iterable<?> self, Object initialValue) {
- return sum(self.iterator(), initialValue, false);
... 6988 lines suppressed ...
[groovy] 02/02: GROOVY-11145: add `join()` example
Posted by em...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 32f49c3538d4389cf8de5d2441e779cdf7cb6767
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Aug 2 12:12:16 2023 -0500
GROOVY-11145: add `join()` example
---
.../groovy/runtime/DefaultGroovyMethods.java | 40 ++++++++++------------
1 file changed, 18 insertions(+), 22 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index 9ee4c13d01..bc0cf3ee39 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -144,6 +144,7 @@ import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
+import java.util.StringJoiner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
@@ -7129,44 +7130,39 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
}
/**
- * Concatenates the <code>toString()</code> representation of each
- * item from the iterator, with the given String as a separator between
- * each item. The iterator will become exhausted of elements after
- * determining the resulting conjoined value.
+ * Concatenates the <code>toString()</code> representation of each item from
+ * the Iterator, with the given String as a separator between each item. The
+ * iterator will become exhausted of elements after producing the resulting
+ * conjoined value.
*
- * @param self an Iterator of items
+ * @param self an Iterator of objects
* @param separator a String separator
* @return the joined String
* @since 1.5.5
*/
- public static String join(Iterator<?> self, String separator) {
- Objects.requireNonNull(self);
- if (separator == null) separator = "";
- StringBuilder buffer = new StringBuilder();
- boolean first = true;
+ public static String join(final Iterator<?> self, final String separator) {
+ StringJoiner joiner = new StringJoiner(separator != null ? separator : "");
while (self.hasNext()) {
- Object value = self.next();
- if (first) {
- first = false;
- } else {
- buffer.append(separator);
- }
- buffer.append(FormatHelper.toString(value));
+ Object obj = self.next();
+ String str = FormatHelper.toString(obj);
+ joiner.add(str);
}
- return buffer.toString();
+ return joiner.toString();
}
/**
- * Concatenates the <code>toString()</code> representation of each
- * item in this Iterable, with the given String as a separator between each item.
- * <pre class="groovyTestCase">assert "1, 2, 3" == [1,2,3].join(", ")</pre>
+ * Concatenates the <code>toString()</code> representation of each item from
+ * the Iterable, with the given String as a separator between each item.
+ * <p>
+ * <pre class="groovyTestCase">assert [1,2,3].join() == "123"</pre>
+ * <pre class="groovyTestCase">assert [1,2,3].join(", ") == "1, 2, 3"</pre>
*
* @param self an Iterable of objects
* @param separator a String separator
* @return the joined String
* @since 1.0
*/
- public static String join(Iterable<?> self, String separator) {
+ public static String join(final Iterable<?> self, final String separator) {
return join(self.iterator(), separator);
}