public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport
public static String reverse(String self)
provides a reverse()
method for String
.
NOTE: While this class contains many 'public' static methods, it is primarily regarded as an internal class (its internal package name suggests this also). We value backwards compatibility of these methods when used within Groovy but value less backwards compatibility at the Java method call level. I.e. future versions of Groovy may remove or move a method call in this file but would normally aim to keep the method available from within Groovy.
DefaultGroovyMethodsSupport.RangeInfo
Modifier and Type | Field and Description |
---|---|
static Class[] |
additionals |
Constructor and Description |
---|
DefaultGroovyMethods() |
Modifier and Type | Method and Description |
---|---|
static double |
abs(Double number)
Get the absolute value
|
static float |
abs(Float number)
Get the absolute value
|
static long |
abs(Long number)
Get the absolute value
|
static int |
abs(Number number)
Get the absolute value
|
static Socket |
accept(ServerSocket serverSocket,
boolean runInANewThread,
Closure closure)
Accepts a connection and passes the resulting Socket to the closure
which runs in a new Thread or the calling thread, as needed.
|
static Socket |
accept(ServerSocket serverSocket,
Closure closure)
Accepts a connection and passes the resulting Socket to the closure
which runs in a new Thread.
|
static <T> boolean |
addAll(Collection<T> self,
T[] items)
Modifies the collection by adding all of the elements in the specified array to the collection.
|
static <T> boolean |
addAll(List<T> self,
int index,
T[] items)
Modifies this list by inserting all of the elements in the specified array into the
list at the specified position.
|
static void |
addShutdownHook(Object self,
Closure closure)
Allows the usage of addShutdownHook without getting the runtime first.
|
static BitSet |
and(BitSet left,
BitSet right)
Bitwise AND together two BitSets.
|
static Boolean |
and(Boolean left,
Boolean right)
Logical conjunction of two boolean operators.
|
static Number |
and(Number left,
Number right)
Bitwise AND together two Numbers.
|
static <K,V> boolean |
any(Map<K,V> self,
Closure<?> closure)
Iterates over the entries of a map, and checks whether a predicate is
valid for at least one entry.
|
static boolean |
any(Object self)
Iterates over the elements of a collection, and checks whether at least
one element is true according to the Groovy Truth.
|
static boolean |
any(Object self,
Closure closure)
Iterates over the contents of an object or collection, and checks whether a
predicate is valid for at least one element.
|
static void |
append(File file,
byte[] bytes)
Append bytes to the end of a File.
|
static void |
append(File self,
InputStream stream)
Append binary data to the file.
|
static void |
append(File file,
Object text)
Append the text at the end of the File.
|
static void |
append(File file,
Object text,
String charset)
Append the text at the end of the File, using a specified encoding.
|
static boolean |
asBoolean(Boolean bool)
Coerce an Boolean instance to a boolean value.
|
static boolean |
asBoolean(boolean[] array)
Coerces a boolean array to a boolean value.
|
static boolean |
asBoolean(byte[] array)
Coerces a byte array to a boolean value.
|
static boolean |
asBoolean(char[] array)
Coerces a char array to a boolean value.
|
static boolean |
asBoolean(Character character)
Coerce a character to a boolean value.
|
static boolean |
asBoolean(CharSequence string)
Coerce a string (an instance of CharSequence) to a boolean value.
|
static boolean |
asBoolean(Collection collection)
Coerce a collection instance to a boolean value.
|
static boolean |
asBoolean(double[] array)
Coerces a double array to a boolean value.
|
static boolean |
asBoolean(Enumeration enumeration)
Coerce an enumeration instance to a boolean value.
|
static boolean |
asBoolean(float[] array)
Coerces a float array to a boolean value.
|
static boolean |
asBoolean(int[] array)
Coerces an int array to a boolean value.
|
static boolean |
asBoolean(Iterator iterator)
Coerce an iterator instance to a boolean value.
|
static boolean |
asBoolean(long[] array)
Coerces a long array to a boolean value.
|
static boolean |
asBoolean(Map map)
Coerce a map instance to a boolean value.
|
static boolean |
asBoolean(Matcher matcher)
Coerce a Matcher instance to a boolean value.
|
static boolean |
asBoolean(Number number)
Coerce a number to a boolean value.
|
static boolean |
asBoolean(Object object)
Coerce an object instance to a boolean value.
|
static boolean |
asBoolean(Object[] array)
Coerce an Object array to a boolean value.
|
static boolean |
asBoolean(short[] array)
Coerces a short array to a boolean value.
|
static <T> Collection<T> |
asImmutable(Collection<? extends T> self)
A convenience method for creating an immutable Collection.
|
static <T> List<T> |
asImmutable(List<? extends T> self)
A convenience method for creating an immutable list
|
static <K,V> Map<K,V> |
asImmutable(Map<? extends K,? extends V> self)
A convenience method for creating an immutable map.
|
static <T> Set<T> |
asImmutable(Set<? extends T> self)
A convenience method for creating an immutable list.
|
static <K,V> SortedMap<K,V> |
asImmutable(SortedMap<K,? extends V> self)
A convenience method for creating an immutable sorted map.
|
static <T> SortedSet<T> |
asImmutable(SortedSet<T> self)
A convenience method for creating an immutable sorted set.
|
static <T> List<T> |
asList(Collection<T> self)
Converts this Collection to a List.
|
static <T> Collection<T> |
asSynchronized(Collection<T> self)
A convenience method for creating a synchronized Collection.
|
static <T> List<T> |
asSynchronized(List<T> self)
A convenience method for creating a synchronized List.
|
static <K,V> Map<K,V> |
asSynchronized(Map<K,V> self)
A convenience method for creating a synchronized Map.
|
static <T> Set<T> |
asSynchronized(Set<T> self)
A convenience method for creating a synchronized Set.
|
static <K,V> SortedMap<K,V> |
asSynchronized(SortedMap<K,V> self)
A convenience method for creating a synchronized SortedMap.
|
static <T> SortedSet<T> |
asSynchronized(SortedSet<T> self)
A convenience method for creating a synchronized SortedSet.
|
static <T> T |
asType(CharSequence self,
Class<T> c)
Provides a method to perform custom 'dynamic' type conversion
to the given class using the
as operator. |
static <T> T |
asType(Closure cl,
Class<T> clazz)
Coerces the closure to an implementation of the given class.
|
static <T> T |
asType(Collection col,
Class<T> clazz)
Converts the given collection to another type.
|
static <T> T |
asType(File f,
Class<T> c)
Converts this File to a
Writable or delegates to default
asType(java.lang.Object, java.lang.Class) . |
static <T> T |
asType(GString self,
Class<T> c)
Converts the GString to a File, or delegates to the default
asType(java.lang.Object, java.lang.Class) |
static <T> T |
asType(Map map,
Class<T> clazz)
Coerces this map to the given type, using the map's keys as the public
method names, and values as the implementation.
|
static <T> T |
asType(Number self,
Class<T> c)
Transform this number to a the given type, using the 'as' operator.
|
static <T> T |
asType(Object[] ary,
Class<T> clazz)
Converts the given array to either a List, Set, or
SortedSet.
|
static <T> T |
asType(Object obj,
Class<T> type)
Converts a given object to a type.
|
static <T> T |
asType(String self,
Class<T> c)
Provides a method to perform custom 'dynamic' type conversion
to the given class using the
as operator. |
static File |
asWritable(File file)
Converts this File to a
Writable . |
static File |
asWritable(File file,
String encoding)
Allows a file to return a Writable implementation that can output itself
to a Writer stream.
|
static BitSet |
bitwiseNegate(BitSet self)
Bitwise NEGATE a BitSet.
|
static Pattern |
bitwiseNegate(CharSequence self)
Turns a CharSequence into a regular expression Pattern
|
static Pattern |
bitwiseNegate(String self)
Turns a String into a regular expression Pattern
|
protected static <T> T |
callClosureForLine(Closure<T> closure,
String line,
int counter) |
protected static <T> T |
callClosureForMapEntry(Closure<T> closure,
Map.Entry entry) |
protected static <T> T |
callClosureForMapEntryAndCounter(Closure<T> closure,
Map.Entry entry,
int counter) |
static CharSequence |
capitalize(CharSequence self)
Convenience method to capitalize the first letter of a CharSequence.
|
static String |
capitalize(String self)
Convenience method to capitalize the first letter of a string
(typically the first letter of a word).
|
static CharSequence |
center(CharSequence self,
Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered.
|
static CharSequence |
center(CharSequence self,
Number numberOfChars,
CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, appending the supplied padding CharSequence around the original as many times as needed keeping it centered.
|
static String |
center(String self,
Number numberOfChars)
Pad a String to a minimum length specified by numberOfChars by adding the space character around it as many times as needed so that it remains centered.
|
static String |
center(String self,
Number numberOfChars,
String padding)
Pad a String to a minimum length specified by numberOfChars, appending the supplied padding String around the original as many times as needed keeping it centered.
|
static <T> List<T> |
collect(Collection<?> self,
Closure<T> closure)
Iterates through this collection transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values.
|
static <T> Collection<T> |
collect(Collection<?> self,
Collection<T> collection,
Closure<? extends T> closure)
Iterates through this collection transforming each value into a new value using the closure
as a transformer, returning an initial collection plus the transformed values.
|
static <T> Collection<T> |
collect(Map<?,?> self,
Collection<T> collection,
Closure<? extends T> closure)
Iterates through this Map transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values.
|
static <T> List<T> |
collect(Map self,
Closure<T> closure)
Iterates through this Map transforming each entry into a new value using the closure
as a transformer, returning a list of transformed values.
|
static <T> List<T> |
collect(Object self,
Closure<T> closure)
Iterates through this object transforming each value into a new value using the
closure as a transformer, returning a list of transformed values.
|
static <T> Collection<T> |
collect(Object self,
Collection<T> collection,
Closure<? extends T> closure)
Iterates through this object transforming each object into a new value using the closure
as a transformer and adding it to the collection, returning the resulting collection.
|
static List |
collectAll(Collection self,
Closure closure)
Deprecated.
Use collectNested instead
|
static Collection |
collectAll(Collection self,
Collection collection,
Closure closure)
Deprecated.
Use collectNested instead
|
static <K,V> Map<K,V> |
collectEntries(Collection<?> self,
Closure<?> closure)
Iterates through this Collection transforming each item using the closure
as a transformer into a map entry, returning a map of the transformed entries.
|
static <K,V> Map<K,V> |
collectEntries(Collection<?> self,
Map<K,V> result,
Closure<?> closure)
Iterates through this Collection transforming each item using the closure
as a transformer into a map entry, returning a map of the transformed entries.
|
static Map<?,?> |
collectEntries(Map<?,?> self,
Closure<?> closure)
Iterates through this Map transforming each entry using the closure
as a transformer, returning a map of the transformed entries.
|
static <K,V> Map<K,V> |
collectEntries(Map<?,?> self,
Map<K,V> result,
Closure<?> closure)
Iterates through this Map transforming each entry using the closure
as a transformer, returning a map of the transformed entries.
|
static <K,V> Map<K,V> |
collectEntries(Object[] self,
Closure<?> closure)
Iterates through this array transforming each item using the closure
as a transformer into a map entry, returning a map of the transformed entries.
|
static <K,V> Map<K,V> |
collectEntries(Object[] self,
Map<K,V> result,
Closure<?> closure)
Iterates through this array transforming each item using the closure
as a transformer into a map entry, returning a map of the transformed entries.
|
static <T> Collection<T> |
collectMany(Collection self,
Closure<Collection<T>> closure)
Projects each item from a source collection to a collection and concatenates (flattens) the resulting collections into a single one.
|
static <T> Collection<T> |
collectMany(Iterator<Object> self,
Closure<Collection<T>> closure)
Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single one.
|
static <T> Collection<T> |
collectMany(Object[] self,
Closure<Collection<T>> closure)
Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single one.
|
static List |
collectNested(Collection self,
Closure closure)
Recursively iterates through this collection transforming each non-Collection value
into a new value using the closure as a transformer.
|
static Collection |
collectNested(Collection self,
Collection collection,
Closure closure)
Recursively iterates through this collection transforming each non-Collection value
into a new value using the closure as a transformer.
|
static List |
combinations(Collection self)
Adds GroovyCollections#combinations(Collection) as a method on collections.
|
static int |
compareTo(Character left,
Character right)
Compare two Characters.
|
static int |
compareTo(Character left,
Number right)
Compare a Character and a Number.
|
static int |
compareTo(Number left,
Character right)
Compare a Number and a Character.
|
static int |
compareTo(Number left,
Number right)
Compare two Numbers.
|
static boolean |
contains(CharSequence self,
CharSequence text)
Provide an implementation of contains() like
Collection.contains(java.lang.Object) to make CharSequences more polymorphic. |
static boolean |
contains(String self,
String text)
Provide an implementation of contains() like
Collection.contains(java.lang.Object) to make Strings more polymorphic. |
static boolean |
containsAll(Collection self,
Object[] items)
Returns true if this collection contains all of the elements
in the specified array.
|
static Number |
count(boolean[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(byte[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(char[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static int |
count(CharSequence self,
CharSequence text)
Count the number of occurrences of a sub CharSequence.
|
static Number |
count(Collection self,
Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this collection.
|
static Number |
count(Collection self,
Object value)
Counts the number of occurrences of the given value inside this collection.
|
static Number |
count(double[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(float[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(int[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(Iterator self,
Closure closure)
Counts the number of occurrences which satisfy the given closure from the
items within this Iterator.
|
static Number |
count(Iterator self,
Object value)
Counts the number of occurrences of the given value from the
items within this Iterator.
|
static Number |
count(long[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(Map self,
Closure<?> closure)
Counts the number of occurrences which satisfy the given closure from inside this map.
|
static Number |
count(Object[] self,
Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this array.
|
static Number |
count(Object[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static Number |
count(short[] self,
Object value)
Counts the number of occurrences of the given value inside this array.
|
static int |
count(String self,
String text)
Count the number of occurrences of a substring.
|
static <K> Map<K,Integer> |
countBy(Collection self,
Closure<K> closure)
Sorts all collection members into groups determined by the supplied mapping
closure and counts the group size.
|
static <K> Map<K,Integer> |
countBy(Iterator self,
Closure<K> closure)
Sorts all iterator items into groups determined by the supplied mapping
closure and counts the group size.
|
static <K> Map<K,Integer> |
countBy(Map self,
Closure<K> closure)
Groups the members of a map into groups determined by the
supplied mapping closure and counts the frequency of the created groups.
|
static <K> Map<K,Integer> |
countBy(Object[] self,
Closure<K> closure)
Sorts all array members into groups determined by the supplied mapping
closure and counts the group size.
|
protected static StringBufferWriter |
createStringBufferWriter(StringBuffer self) |
protected static StringWriter |
createStringWriter(String self) |
static boolean |
deleteDir(File self)
Deletes a directory with all contained files and subdirectories.
|
static CharSequence |
denormalize(CharSequence self)
Return a CharSequence with lines (separated by LF, CR/LF, or CR)
terminated by the platform specific line separator.
|
static String |
denormalize(String self)
Return a String with lines (separated by LF, CR/LF, or CR)
terminated by the platform specific line separator.
|
static boolean |
disjoint(Collection left,
Collection right)
Returns
true if the intersection of two collections is empty. |
static Number |
div(Character left,
Character right)
Divide one Character by another.
|
static Number |
div(Character left,
Number right)
Divide a Character by a Number.
|
static Number |
div(Number left,
Character right)
Divide a Number by a Character.
|
static void |
downto(BigDecimal self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(BigInteger self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(double self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(Double self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(float self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(Float self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(long self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(Long self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static void |
downto(Number self,
Number to,
Closure closure)
Iterates from this number down to the given number, inclusive,
decrementing by one each time.
|
static CharSequence |
drop(CharSequence self,
int num)
Drops the given number of chars from the head of this CharSequence
if they are available.
|
static <T> Iterator<T> |
drop(Iterator<T> self,
int num)
Drops the given number of elements from the head of this iterator if they are available.
|
static <T> List<T> |
drop(List<T> self,
int num)
Drops the given number of elements from the head of this list
if they are available.
|
static <K,V> Map<K,V> |
drop(Map<K,V> self,
int num)
Drops the given number of key/value pairs from the head of this map if they are available.
|
static <T> T[] |
drop(T[] self,
int num)
Drops the given number of elements from the head of this array
if they are available.
|
static String |
dump(Object self)
Generates a detailed dump string of an object showing its class,
hashCode and fields.
|
static <K,V> Map<K,V> |
each(Map<K,V> self,
Closure closure)
Allows a Map to be iterated through using a closure.
|
static <T> T |
each(T self,
Closure closure)
Iterates through an aggregate type or data structure,
passing each item to the given closure.
|
static void |
eachByte(byte[] self,
Closure closure)
Traverse through each byte of this byte array.
|
static void |
eachByte(Byte[] self,
Closure closure)
Traverse through each byte of this Byte array.
|
static void |
eachByte(File self,
Closure closure)
Traverse through each byte of this File
|
static void |
eachByte(File self,
int bufferLen,
Closure closure)
Traverse through the bytes of this File, bufferLen bytes at a time.
|
static void |
eachByte(InputStream is,
Closure closure)
Traverse through each byte of the specified stream.
|
static void |
eachByte(InputStream is,
int bufferLen,
Closure closure)
Traverse through each the specified stream reading bytes into a buffer
and calling the 2 parameter closure with this buffer and the number of bytes.
|
static void |
eachByte(URL url,
Closure closure)
Reads the InputStream from this URL, passing each byte to the given
closure.
|
static void |
eachByte(URL url,
int bufferLen,
Closure closure)
Reads the InputStream from this URL, passing a byte[] and a number of bytes
to the given closure.
|
static void |
eachDir(File self,
Closure closure)
Invokes the closure for each subdirectory in this directory,
ignoring regular files.
|
static void |
eachDirMatch(File self,
Object nameFilter,
Closure closure)
Invokes the closure for each subdirectory whose name (dir.name) matches the given nameFilter in the given directory
- calling the
isCase(java.lang.Object, java.lang.Object) method to determine if a match occurs. |
static void |
eachDirRecurse(File self,
Closure closure)
Invokes the closure for each descendant directory of this directory.
|
static void |
eachFile(File self,
Closure closure)
Invokes the closure for each 'child' file in this 'parent' folder/directory.
|
static void |
eachFile(File self,
FileType fileType,
Closure closure)
Invokes the closure for each 'child' file in this 'parent' folder/directory.
|
static void |
eachFileMatch(File self,
FileType fileType,
Object nameFilter,
Closure closure)
Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory
- calling the
isCase(java.lang.Object, java.lang.Object) method to determine if a match occurs. |
static void |
eachFileMatch(File self,
Object nameFilter,
Closure closure)
Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory
- calling the
isCase(java.lang.Object, java.lang.Object) method to determine if a match occurs. |
static void |
eachFileRecurse(File self,
Closure closure)
Invokes the closure for each descendant file in this directory.
|
static void |
eachFileRecurse(File self,
FileType fileType,
Closure closure)
Invokes the closure for each descendant file in this directory.
|
static <T> T |
eachLine(CharSequence self,
Closure<T> closure)
Iterates through this CharSequence line by line.
|
static <T> T |
eachLine(CharSequence self,
int firstLine,
Closure<T> closure)
Iterates through this CharSequence line by line.
|
static <T> T |
eachLine(File self,
Closure<T> closure)
Iterates through this file line by line.
|
static <T> T |
eachLine(File self,
int firstLine,
Closure<T> closure)
Iterates through this file line by line.
|
static <T> T |
eachLine(File self,
String charset,
Closure<T> closure)
Iterates through this file line by line.
|
static <T> T |
eachLine(File self,
String charset,
int firstLine,
Closure<T> closure)
Iterates through this file line by line.
|
static <T> T |
eachLine(InputStream stream,
Closure<T> closure)
Iterates through this stream, passing each line to the given 1 or 2 arg closure.
|
static <T> T |
eachLine(InputStream stream,
int firstLine,
Closure<T> closure)
Iterates through this stream, passing each line to the given 1 or 2 arg closure.
|
static <T> T |
eachLine(InputStream stream,
String charset,
Closure<T> closure)
Iterates through this stream reading with the provided charset, passing each line to the
given 1 or 2 arg closure.
|
static <T> T |
eachLine(InputStream stream,
String charset,
int firstLine,
Closure<T> closure)
Iterates through this stream reading with the provided charset, passing each line to
the given 1 or 2 arg closure.
|
static <T> T |
eachLine(Reader self,
Closure<T> closure)
Iterates through the given reader line by line.
|
static <T> T |
eachLine(Reader self,
int firstLine,
Closure<T> closure)
Iterates through the given reader line by line.
|
static <T> T |
eachLine(String self,
Closure<T> closure)
Iterates through this String line by line.
|
static <T> T |
eachLine(String self,
int firstLine,
Closure<T> closure)
Iterates through this String line by line.
|
static <T> T |
eachLine(URL url,
Closure<T> closure)
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure.
|
static <T> T |
eachLine(URL url,
int firstLine,
Closure<T> closure)
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure.
|
static <T> T |
eachLine(URL url,
String charset,
Closure<T> closure)
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure.
|
static <T> T |
eachLine(URL url,
String charset,
int firstLine,
Closure<T> closure)
Iterates through the lines read from the URL's associated input stream passing each
line to the given 1 or 2 arg closure.
|
static String |
eachMatch(CharSequence self,
CharSequence regex,
Closure closure)
Process each regex group matched substring of the given CharSequence.
|
static String |
eachMatch(CharSequence self,
Pattern pattern,
Closure closure)
Process each regex group matched substring of the given pattern.
|
static String |
eachMatch(String self,
Pattern pattern,
Closure closure)
Process each regex group matched substring of the given pattern.
|
static String |
eachMatch(String self,
String regex,
Closure closure)
Process each regex group matched substring of the given string.
|
static void |
eachObject(File self,
Closure closure)
Iterates through the given file object by object.
|
static void |
eachObject(ObjectInputStream ois,
Closure closure)
Iterates through the given object stream object by object.
|
static <T> Iterator<List<T>> |
eachPermutation(Collection<T> self,
Closure closure)
Iterates over all permutations of a collection, running a closure for each iteration.
|
static <K,V> Map<K,V> |
eachWithIndex(Map<K,V> self,
Closure closure)
Allows a Map to be iterated through using a closure.
|
static <T> T |
eachWithIndex(T self,
Closure closure)
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.
|
static boolean |
equals(int[] left,
int[] right)
Compare the contents of this array to the contents of the given array.
|
static boolean |
equals(List left,
List right)
Compare the contents of two Lists.
|
static boolean |
equals(List left,
Object[] right)
Determines if the contents of this list are equal to the
contents of the given array in the same order.
|
static boolean |
equals(Map self,
Map other)
Compares two Maps treating coerced numerical values as identical.
|
static boolean |
equals(Object[] left,
List right)
Determines if the contents of this array are equal to the
contents of the given list, in the same order.
|
static <T> boolean |
equals(Set<T> self,
Set<T> other)
Compare the contents of two Sets for equality using Groovy's coercion rules.
|
static <K,V> boolean |
every(Map<K,V> self,
Closure closure)
Iterates over the entries of a map, and checks whether a predicate is
valid for all entries.
|
static boolean |
every(Object self)
Iterates over every element of a collection, and checks whether all
elements are
true according to the Groovy Truth. |
static boolean |
every(Object self,
Closure closure)
Used to determine if the given predicate closure is valid (i.e.
|
static Process |
execute(List commands)
Executes the command specified by the given list.
|
static Process |
execute(List commands,
List envp,
File dir)
Executes the command specified by the given list,
with the environment defined by
envp and under the working directory dir . |
static Process |
execute(List commands,
String[] envp,
File dir)
Executes the command specified by the given list,
with the environment defined by
envp and under the working directory dir . |
static Process |
execute(String self)
Executes the command specified by
self as a command-line process. |
static Process |
execute(String[] commandArray)
Executes the command specified by the given
String array. |
static Process |
execute(String[] commandArray,
List envp,
File dir)
Executes the command specified by the
String array given in the first parameter,
with the environment defined by envp and under the working directory dir . |
static Process |
execute(String[] commandArray,
String[] envp,
File dir)
Executes the command specified by the
String array given in the first parameter,
with the environment defined by envp and under the working directory dir . |
static Process |
execute(String self,
List envp,
File dir)
Executes the command specified by
self with environment defined
by envp and under the working directory dir . |
static Process |
execute(String self,
String[] envp,
File dir)
Executes the command specified by
self with environment defined by envp
and under the working directory dir . |
static CharSequence |
expand(CharSequence self)
Expands all tabs into spaces with tabStops of size 8.
|
static CharSequence |
expand(CharSequence self,
int tabStop)
Expands all tabs into spaces.
|
static String |
expand(String self)
Expands all tabs into spaces with tabStops of size 8.
|
static String |
expand(String self,
int tabStop)
Expands all tabs into spaces.
|
static CharSequence |
expandLine(CharSequence self,
int tabStop)
Expands all tabs into spaces.
|
static String |
expandLine(String self,
int tabStop)
Expands all tabs into spaces.
|
static Writable |
filterLine(File self,
Closure closure)
Filters the lines of a File and creates a Writable in return to
stream the filtered lines.
|
static Writable |
filterLine(File self,
String charset,
Closure closure)
Filters the lines of a File and creates a Writable in return to
stream the filtered lines.
|
static void |
filterLine(File self,
Writer writer,
Closure closure)
Filter the lines from this File, and write them to the given writer based
on the given closure predicate.
|
static void |
filterLine(File self,
Writer writer,
String charset,
Closure closure)
Filter the lines from this File, and write them to the given writer based
on the given closure predicate.
|
static Writable |
filterLine(InputStream self,
Closure predicate)
Filter lines from an input stream using a closure predicate.
|
static Writable |
filterLine(InputStream self,
String charset,
Closure predicate)
Filter lines from an input stream using a closure predicate.
|
static void |
filterLine(InputStream self,
Writer writer,
Closure predicate)
Uses a closure to filter lines from this InputStream and pass them to
the given writer.
|
static void |
filterLine(InputStream self,
Writer writer,
String charset,
Closure predicate)
Uses a closure to filter lines from this InputStream and pass them to
the given writer.
|
static Writable |
filterLine(Reader reader,
Closure closure)
Filter the lines from this Reader, and return a Writable which can be
used to stream the filtered lines to a destination.
|
static void |
filterLine(Reader reader,
Writer writer,
Closure closure)
Filter the lines from a reader and write them on the writer,
according to a closure which returns true if the line should be included.
|
static Writable |
filterLine(URL self,
Closure predicate)
Filter lines from a URL using a closure predicate.
|
static Writable |
filterLine(URL self,
String charset,
Closure predicate)
Filter lines from a URL using a closure predicate.
|
static void |
filterLine(URL self,
Writer writer,
Closure predicate)
Uses a closure to filter lines from this URL and pass them to
the given writer.
|
static void |
filterLine(URL self,
Writer writer,
String charset,
Closure predicate)
Uses a closure to filter lines from this URL and pass them to
the given writer.
|
static CharSequence |
find(CharSequence self,
CharSequence regex)
Finds the first occurrence of a regular expression CharSequence within a CharSequence.
|
static CharSequence |
find(CharSequence self,
CharSequence regex,
Closure closure)
Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence.
|
static CharSequence |
find(CharSequence self,
Pattern pattern)
Finds the first occurrence of a compiled regular expression Pattern within a CharSequence.
|
static CharSequence |
find(CharSequence self,
Pattern pattern,
Closure closure)
Returns the result of calling a closure with the first occurrence of a regular expression found within a
CharSequence.
|
static <T> T |
find(Collection<T> self)
Finds the first item matching the IDENTITY Closure (i.e.
|
static <T> T |
find(Collection<T> self,
Closure closure)
Finds the first value matching the closure condition.
|
static <K,V> Map.Entry<K,V> |
find(Map<K,V> self,
Closure<?> closure)
Finds the first entry matching the closure condition.
|
static Object |
find(Object self)
Finds the first item matching the IDENTITY Closure (i.e.
|
static Object |
find(Object self,
Closure closure)
Finds the first value matching the closure condition
|
static String |
find(String self,
Pattern pattern)
Finds the first occurrence of a compiled regular expression Pattern within a String.
|
static String |
find(String self,
Pattern pattern,
Closure closure)
Returns the result of calling a closure with the first occurrence of a compiled regular expression found within a String.
|
static String |
find(String self,
String regex)
Finds the first occurrence of a regular expression String within a String.
|
static String |
find(String self,
String regex,
Closure closure)
Returns the result of calling a closure with the first occurrence of a regular expression found within a String.
|
static List<CharSequence> |
findAll(CharSequence self,
CharSequence regex)
Returns a (possibly empty) list of all occurrences of a regular expression (in CharSequence format) found within a CharSequence.
|
static <T> List<T> |
findAll(CharSequence self,
CharSequence regex,
Closure<T> closure)
Finds all occurrences of a capturing regular expression CharSequence within a CharSequence.
|
static List<CharSequence> |
findAll(CharSequence self,
Pattern pattern)
Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a CharSequence.
|
static <T> List<T> |
findAll(CharSequence self,
Pattern pattern,
Closure<T> closure)
Finds all occurrences of a compiled regular expression Pattern within a CharSequence.
|
static <T> Collection<T> |
findAll(Collection<T> self)
Finds the items matching the IDENTITY Closure (i.e.
|
static <T> Collection<T> |
findAll(Collection<T> self,
Closure closure)
Finds all values matching the closure condition.
|
static <K,V> Map<K,V> |
findAll(Map<K,V> self,
Closure closure)
Finds all entries matching the closure condition.
|
static Collection |
findAll(Object self)
Finds all items matching the IDENTITY Closure (i.e.
|
static Collection |
findAll(Object self,
Closure closure)
Finds all items matching the closure condition.
|
static List<String> |
findAll(String self,
Pattern pattern)
Returns a (possibly empty) list of all occurrences of a regular expression (in Pattern format) found within a String.
|
static <T> List<T> |
findAll(String self,
Pattern pattern,
Closure<T> closure)
Finds all occurrences of a compiled regular expression Pattern within a String.
|
static List<String> |
findAll(String self,
String regex)
Returns a (possibly empty) list of all occurrences of a regular expression (in String format) found within a String.
|
static <T> List<T> |
findAll(String self,
String regex,
Closure<T> closure)
Finds all occurrences of a regular expression string within a String.
|
static int |
findIndexOf(Object self,
Closure closure)
Iterates over the elements of an iterable collection of items and returns
the index of the first item that matches the condition specified in the closure.
|
static int |
findIndexOf(Object self,
int startIndex,
Closure closure)
Iterates over the elements of an iterable collection of items, starting from a
specified startIndex, and returns the index of the first item that matches the
condition specified in the closure.
|
static List<Number> |
findIndexValues(Object self,
Closure closure)
Iterates over the elements of an iterable collection of items and returns
the index values of the items that match the condition specified in the closure.
|
static List<Number> |
findIndexValues(Object self,
Number startIndex,
Closure closure)
Iterates over the elements of an iterable collection of items, starting from
a specified startIndex, and returns the index values of the items that match
the condition specified in the closure.
|
static int |
findLastIndexOf(Object self,
Closure closure)
Iterates over the elements of an iterable collection of items and returns
the index of the last item that matches the condition specified in the closure.
|
static int |
findLastIndexOf(Object self,
int startIndex,
Closure closure)
Iterates over the elements of an iterable collection of items, starting
from a specified startIndex, and returns the index of the last item that
matches the condition specified in the closure.
|
static <T> T |
findResult(Collection<?> self,
Closure<T> closure)
Iterates through the collection calling the given closure for each item but stopping once the first non-null
result is found and returning that result.
|
static <T,U extends T,V extends T> |
findResult(Collection<?> self,
U defaultResult,
Closure<V> closure)
Iterates through the collection calling the given closure for each item but stopping once the first non-null
result is found and returning that result.
|
static <T> T |
findResult(Map<?,?> self,
Closure<T> closure)
Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned.
|
static <T,U extends T,V extends T> |
findResult(Map<?,?> self,
U defaultResult,
Closure<V> closure)
Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned.
|
static Object |
findResult(Object self,
Closure closure)
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.
|
static Object |
findResult(Object self,
Object defaultResult,
Closure closure)
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.
|
static <T> Collection<T> |
findResults(Collection<?> self,
Closure<T> filteringTransform)
Iterates through the collection transforming items using the supplied closure
and collecting any non-null results.
|
static <T> Collection<T> |
findResults(Map<?,?> self,
Closure<T> filteringTransform)
Iterates through the map transforming items using the supplied closure
and collecting any non-null results.
|
static <T> T |
first(List<T> self)
Returns the first item from the List.
|
static <T> T |
first(T[] self)
Returns the first item from the Object array.
|
static Collection |
flatten(boolean[] self)
Flatten an array.
|
static Collection |
flatten(byte[] self)
Flatten an array.
|
static Collection |
flatten(char[] self)
Flatten an array.
|
static Collection<?> |
flatten(Collection<?> self)
Flatten a collection.
|
static <T> Collection<T> |
flatten(Collection<T> self,
Closure<? extends T> flattenUsing)
Flatten a collection.
|
static Collection |
flatten(double[] self)
Flatten an array.
|
static Collection |
flatten(float[] self)
Flatten an array.
|
static Collection |
flatten(int[] self)
Flatten an array.
|
static Collection |
flatten(long[] self)
Flatten an array.
|
static Collection |
flatten(Object[] self)
Flatten an array.
|
static Collection |
flatten(short[] self)
Flatten an array.
|
static <K,V> V |
get(Map<K,V> map,
K key,
V defaultValue)
Looks up an item in a Map for the given key and returns the value - unless
there is no entry for the given key in which case add the default value
to the map and return that.
|
static boolean |
getAt(BitSet self,
int index)
Support the subscript operator for a Bitset
|
static BitSet |
getAt(BitSet self,
IntRange range)
Support retrieving a subset of a BitSet using a Range
|
static List<Boolean> |
getAt(boolean[] array,
Collection indices)
Support the subscript operator with a collection for a boolean array
|
static List<Boolean> |
getAt(boolean[] array,
IntRange range)
Support the subscript operator with an IntRange for a boolean array
|
static List<Boolean> |
getAt(boolean[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a byte array
|
static List<Boolean> |
getAt(boolean[] array,
Range range)
Support the subscript operator with a range for a boolean array
|
static List<Byte> |
getAt(byte[] array,
Collection indices)
Support the subscript operator with a collection for a byte array
|
static List<Byte> |
getAt(byte[] array,
IntRange range)
Support the subscript operator with an IntRange for a byte array
|
static List<Byte> |
getAt(byte[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a byte array
|
static List<Byte> |
getAt(byte[] array,
Range range)
Support the subscript operator with a range for a byte array
|
static List<Character> |
getAt(char[] array,
Collection indices)
Support the subscript operator with a collection for a char array
|
static List<Character> |
getAt(char[] array,
IntRange range)
Support the subscript operator with an IntRange for a char array
|
static List<Character> |
getAt(char[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a char array
|
static List<Character> |
getAt(char[] array,
Range range)
Support the subscript operator with a range for a char array
|
static CharSequence |
getAt(CharSequence self,
Collection indices)
Select a List of characters from a CharSequence using a Collection
to identify the indices to be selected.
|
static CharSequence |
getAt(CharSequence text,
EmptyRange range)
Support the range subscript operator for CharSequence or StringBuffer with EmptyRange
|
static CharSequence |
getAt(CharSequence text,
int index)
Support the subscript operator for CharSequence.
|
static CharSequence |
getAt(CharSequence text,
IntRange range)
Support the range subscript operator for CharSequence or StringBuffer with IntRange
|
static CharSequence |
getAt(CharSequence text,
Range range)
Support the range subscript operator for CharSequence
|
static List |
getAt(Collection coll,
String property)
Support the subscript operator for Collection.
|
static List<Double> |
getAt(double[] array,
Collection indices)
Support the subscript operator with a collection for a double array
|
static List<Double> |
getAt(double[] array,
IntRange range)
Support the subscript operator with an IntRange for a double array
|
static List<Double> |
getAt(double[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a double array
|
static List<Double> |
getAt(double[] array,
Range range)
Support the subscript operator with a range for a double array
|
static List<Float> |
getAt(float[] array,
Collection indices)
Support the subscript operator with a collection for a float array
|
static List<Float> |
getAt(float[] array,
IntRange range)
Support the subscript operator with an IntRange for a float array
|
static List<Float> |
getAt(float[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a float array
|
static List<Float> |
getAt(float[] array,
Range range)
Support the subscript operator with a range for a float array
|
static List<Integer> |
getAt(int[] array,
Collection indices)
Support the subscript operator with a collection for an int array
|
static List<Integer> |
getAt(int[] array,
IntRange range)
Support the subscript operator with an IntRange for an int array
|
static List<Integer> |
getAt(int[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for an int array
|
static List<Integer> |
getAt(int[] array,
Range range)
Support the subscript operator with a range for an int array
|
static <T> T |
getAt(Iterator<T> self,
int idx)
Support the subscript operator for an Iterator.
|
static <T> List<T> |
getAt(List<T> self,
Collection indices)
Select a List of items from a List using a Collection to
identify the indices to be selected.
|
static <T> List<T> |
getAt(List<T> self,
EmptyRange range)
Support the range subscript operator for a List.
|
static <T> T |
getAt(List<T> self,
int idx)
Support the subscript operator for a List.
|
static <T> List<T> |
getAt(List<T> self,
Range range)
Support the range subscript operator for a List.
|
static List<Long> |
getAt(long[] array,
Collection indices)
Support the subscript operator with a collection for a long array
|
static List<Long> |
getAt(long[] array,
IntRange range)
Support the subscript operator with an IntRange for a long array
|
static List<Long> |
getAt(long[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a long array
|
static List<Long> |
getAt(long[] array,
Range range)
Support the subscript operator with a range for a long array
|
static <K,V> V |
getAt(Map<K,V> self,
K key)
Support the subscript operator for a Map.
|
static List |
getAt(Matcher self,
Collection indices)
Select a List of values from a Matcher using a Collection
to identify the indices to be selected.
|
static Object |
getAt(Matcher matcher,
int idx)
Support the subscript operator, e.g.
|
static Object |
getAt(Object self,
String property)
Allows the subscript operator to be used to lookup dynamic property values.
|
static List<Short> |
getAt(short[] array,
Collection indices)
Support the subscript operator with a collection for a short array
|
static List<Short> |
getAt(short[] array,
IntRange range)
Support the subscript operator with an IntRange for a short array
|
static List<Short> |
getAt(short[] array,
ObjectRange range)
Support the subscript operator with an ObjectRange for a short array
|
static List<Short> |
getAt(short[] array,
Range range)
Support the subscript operator with a range for a short array
|
static String |
getAt(String self,
Collection indices)
Select a List of characters from a String using a Collection
to identify the indices to be selected.
|
static String |
getAt(String text,
EmptyRange range)
Support the range subscript operator for String with EmptyRange
|
static String |
getAt(String text,
int index)
Support the subscript operator for String.
|
static String |
getAt(String text,
IntRange range)
Support the range subscript operator for String with IntRange
|
static String |
getAt(String text,
Range range)
Support the range subscript operator for String
|
static <T> List<T> |
getAt(T[] self,
Collection indices)
Select a List of items from an Object array using a Collection to
identify the indices to be selected.
|
static <T> List<T> |
getAt(T[] array,
EmptyRange range) |
static <T> List<T> |
getAt(T[] array,
IntRange range) |
static <T> List<T> |
getAt(T[] array,
ObjectRange range) |
static <T> List<T> |
getAt(T[] array,
Range range)
Support the range subscript operator for an Array
|
static byte[] |
getBytes(File file)
Read the content of the File and returns it as a byte[].
|
static byte[] |
getBytes(InputStream is)
Read the content of this InputStream and return it as a byte[].
|
static byte[] |
getBytes(URL url)
Read the content of this URL and returns it as a byte[].
|
static char[] |
getChars(CharSequence self)
Converts the given CharSequence into an array of characters.
|
static char[] |
getChars(String self)
Converts the given String into an array of characters.
|
static int |
getCount(Matcher matcher)
Find the number of Strings matched to the given Matcher.
|
static MetaClass |
getMetaClass(Class c)
Adds a "metaClass" property to all class objects so you can use the syntax
String.metaClass.myMethod = { println "foo" } |
static MetaClass |
getMetaClass(GroovyObject obj)
Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself.
|
static MetaClass |
getMetaClass(Object obj)
Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself.
|
static List<PropertyValue> |
getMetaPropertyValues(Object self)
Retrieves the list of
MetaProperty objects for 'self' and wraps it
in a list of PropertyValue objects that additionally provide
the value for each property of 'self'. |
static Map |
getProperties(Object self)
Convenience method that calls
getMetaPropertyValues(java.lang.Object) (self)
and provides the data in form of simple key/value pairs, i.e. |
static ClassLoader |
getRootLoader(ClassLoader self)
Iterates through the classloader parents until it finds a loader with a class
named "org.codehaus.groovy.tools.RootLoader".
|
protected static List |
getSubList(List self,
List splice) |
static String |
getText(BufferedReader reader)
Read the content of the BufferedReader and return it as a String.
|
static String |
getText(File file)
Read the content of the File and returns it as a String.
|
static String |
getText(File file,
String charset)
Read the content of the File using the specified encoding and return it
as a String.
|
static String |
getText(InputStream is)
Read the content of this InputStream and return it as a String.
|
static String |
getText(InputStream is,
String charset)
Read the content of this InputStream using specified charset and return
it as a String.
|
static String |
getText(Reader reader)
Read the content of the Reader and return it as a String.
|
static String |
getText(URL url)
Read the content of this URL and returns it as a String.
|
static String |
getText(URL url,
Map parameters)
Read the content of this URL and returns it as a String.
|
static String |
getText(URL url,
Map parameters,
String charset)
Read the data from this URL and return it as a String.
|
static String |
getText(URL url,
String charset)
Read the data from this URL and return it as a String.
|
static Collection |
grep(Object self)
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.
|
static Collection |
grep(Object self,
Object filter)
Iterates over the collection of items which this Object represents and returns each item that matches
the given filter - calling the
method used by switch statements. |
protected static <K,T> void |
groupAnswer(Map<K,List<T>> answer,
T element,
K value)
Groups the current element according to the value
|
static <K,T> Map<K,List<T>> |
groupBy(Collection<T> self,
Closure<K> closure)
Sorts all collection members into groups determined by the
supplied mapping closure.
|
static Map |
groupBy(Collection self,
List<Closure> closures)
Sorts all collection members into (sub)groups determined by the supplied
mapping closures.
|
static Map |
groupBy(Collection self,
Object... closures)
Sorts all collection members into (sub)groups determined by the supplied
mapping closures.
|
static <G,K,V> Map<G,Map<K,V>> |
groupBy(Map<K,V> self,
Closure<G> closure)
Groups the members of a map into sub maps determined by the
supplied mapping closure.
|
static Map<Object,Map> |
groupBy(Map self,
List<Closure> closures)
Groups the members of a map into sub maps determined by the supplied
mapping closures.
|
static Map<Object,Map> |
groupBy(Map self,
Object... closures)
Groups the members of a map into sub maps determined by the supplied
mapping closures.
|
static <G,K,V> Map<G,List<Map.Entry<K,V>>> |
groupEntriesBy(Map<K,V> self,
Closure<G> closure)
Groups all map entries into groups determined by the
supplied mapping closure.
|
static boolean |
hasGroup(Matcher matcher)
Check whether a Matcher contains a group or not.
|
static MetaProperty |
hasProperty(Object self,
String name)
Returns true of the implementing MetaClass has a property of the given name
Note that this method will only return true for realised properties and does not take into
account implementation of getProperty or propertyMissing
|
static <T> T |
head(List<T> self)
Returns the first item from the List.
|
static <T> T |
head(T[] self)
Returns the first item from the Object array.
|
static <T> T |
identity(Object self,
Closure<T> closure)
Allows the closure to be called for the object reference self.
|
static Boolean |
implies(Boolean left,
Boolean right)
Logical implication of two boolean operators
|
static <T,U extends T,V extends T> |
inject(Collection self,
U initialValue,
Closure<V> closure)
Iterates through the given Collection, passing in the initial value to
the 2-arg closure along with the first item.
|
static <T,U extends T,V extends T> |
inject(Iterator self,
U initialValue,
Closure<V> closure)
Iterates through the given Iterator, passing in the initial value to
the closure along with the first item.
|
static <T,U extends T,V extends T> |
inject(Map<?,?> self,
U initialValue,
Closure<V> 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).
|
static <T,U extends T,V extends T> |
inject(Object[] self,
U initialValue,
Closure<V> closure)
Iterates through the given array, passing in the initial value to
the closure along with the first item.
|
static <T,U extends T,V extends T> |
inject(Object self,
U initialValue,
Closure<V> closure)
Iterates through the given Object, passing in the initial value to
the closure along with the first item.
|
static String |
inspect(Object self)
Inspects returns the String that matches what would be typed into a
terminal to create this object.
|
static Number |
intdiv(Character left,
Character right)
Integer Divide two Characters.
|
static Number |
intdiv(Character left,
Number right)
Integer Divide a Character by a Number.
|
static Number |
intdiv(Number left,
Character right)
Integer Divide a Number by a Character.
|
static Number |
intdiv(Number left,
Number right)
Integer Divide two Numbers.
|
static <T> Collection<T> |
intersect(Collection<T> left,
Collection<T> right)
Create a Collection composed of the intersection of both collections.
|
static <K,V> Map<K,V> |
intersect(Map<K,V> left,
Map<K,V> right)
Create a Map composed of the intersection of both maps.
|
static Object |
invokeMethod(Object object,
String method,
Object arguments)
Provide a dynamic method invocation method which can be overloaded in
classes to implement dynamic proxies easily.
|
static boolean |
is(Object self,
Object other)
Identity check.
|
static boolean |
isAllWhitespace(CharSequence self)
True if a CharSequence only contains whitespace characters.
|
static boolean |
isAllWhitespace(String self)
True if a String only contains whitespace characters.
|
static boolean |
isBigDecimal(CharSequence self)
Determine if a CharSequence can be parsed as a BigDecimal.
|
static boolean |
isBigDecimal(String self)
Determine if a String can be parsed into a BigDecimal.
|
static boolean |
isBigInteger(CharSequence self)
Determine if a CharSequence can be parsed as a BigInteger.
|
static boolean |
isBigInteger(String self)
Determine if a String can be parsed into a BigInteger.
|
static boolean |
isCase(CharSequence caseValue,
Object switchValue)
'Case' implementation for a CharSequence, which simply calls the equivalent method for String.
|
static boolean |
isCase(Class caseValue,
Object switchValue)
Special 'Case' implementation for Class, which allows testing
for a certain class in a switch statement.
|
static boolean |
isCase(Collection caseValue,
Object switchValue)
'Case' implementation for collections which tests if the 'switch'
operand is contained in any of the 'case' values.
|
static boolean |
isCase(GString caseValue,
Object switchValue)
'Case' implementation for a GString, which simply calls the equivalent method for String.
|
static boolean |
isCase(Map caseValue,
Object switchValue)
'Case' implementation for maps which tests the groovy truth
value obtained using the 'switch' operand as key.
|
static boolean |
isCase(Number caseValue,
Number switchValue)
Special 'case' implementation for all numbers, which delegates to the
compareTo() method for comparing numbers of different
types. |
static boolean |
isCase(Object caseValue,
Object switchValue)
Method for overloading the behavior of the 'case' method in switch statements.
|
static boolean |
isCase(Pattern caseValue,
Object switchValue)
'Case' implementation for the
Pattern class, which allows
testing a String against a number of regular expressions. |
static boolean |
isCase(String caseValue,
Object switchValue)
'Case' implementation for a String, which uses String#equals(Object)
in order to allow Strings to be used in switch statements.
|
static boolean |
isDigit(Character self)
Determines if a character is a digit.
|
static boolean |
isDouble(CharSequence self)
Determine if a CharSequence can be parsed as a Double.
|
static boolean |
isDouble(String self)
Determine if a String can be parsed into a Double.
|
static boolean |
isFloat(CharSequence self)
Determine if a CharSequence can be parsed as a Float.
|
static boolean |
isFloat(String self)
Determine if a String can be parsed into a Float.
|
static boolean |
isInteger(CharSequence self)
Determine if a CharSequence can be parsed as an Integer.
|
static boolean |
isInteger(String self)
Determine if a String can be parsed into an Integer.
|
static boolean |
isLetter(Character self)
Determines if a character is a letter.
|
static boolean |
isLetterOrDigit(Character self)
Determines if a character is a letter or digit.
|
static boolean |
isLong(CharSequence self)
Determine if a CharSequence can be parsed as a Long.
|
static boolean |
isLong(String self)
Determine if a String can be parsed into a Long.
|
static boolean |
isLowerCase(Character self)
Determine if a Character is lowercase.
|
static boolean |
isNumber(CharSequence self)
Determine if a CharSequence can be parsed as a Number.
|
static boolean |
isNumber(String self)
Determine if a String can be parsed into a Number.
|
static boolean |
isUpperCase(Character self)
Determine if a Character is uppercase.
|
static boolean |
isWhitespace(Character self)
Determines if a character is a whitespace character.
|
static Iterator<Byte> |
iterator(DataInputStream self)
Standard iterator for a data input stream which iterates through the
stream content a Byte at a time.
|
static <T> Iterator<T> |
iterator(Enumeration<T> enumeration)
Allows an Enumeration to behave like an Iterator.
|
static Iterator<Byte> |
iterator(InputStream self)
Standard iterator for a input stream which iterates through the stream
content in a byte-based fashion.
|
static <T> Iterator<T> |
iterator(Iterator<T> self)
An identity function for iterators, supporting 'duck-typing' when trying to get an
iterator for each object within a collection, some of which may already be iterators.
|
static Iterator |
iterator(Matcher matcher)
Returns an
Iterator which traverses each match. |
static Iterator |
iterator(Object o)
Attempts to create an Iterator for the given object by first
converting it to a Collection.
|
static Iterator<String> |
iterator(Reader self)
Creates an iterator which will traverse through the reader a line at a time.
|
static <T> Iterator<T> |
iterator(T[] a)
Attempts to create an Iterator for the given object by first
converting it to a Collection.
|
static String |
join(Collection self,
String separator)
Concatenates the
toString() representation of each
item in this collection, with the given String as a separator between
each item. |
static String |
join(Iterator<Object> self,
String separator)
Concatenates the
toString() representation of each
item from the iterator, with the given String as a separator between
each item. |
static String |
join(Object[] self,
String separator)
Concatenates the
toString() representation of each
items in this array, with the given String as a separator between each
item. |
static <T> T |
last(List<T> self)
Returns the last item from the List.
|
static <T> T |
last(T[] self)
Returns the last item from the Object array.
|
static <T> BlockingQueue<T> |
leftShift(BlockingQueue<T> self,
T value)
Overloads the left shift operator to provide an easy way to append
objects to a BlockingQueue.
|
static StringBuilder |
leftShift(CharSequence self,
Object value)
Overloads the left shift operator to provide an easy way to append multiple
objects as string representations to a CharSequence.
|
static <T> Collection<T> |
leftShift(Collection<T> self,
T value)
Overloads the left shift operator to provide an easy way to append
objects to a Collection.
|
static File |
leftShift(File file,
byte[] bytes)
Write bytes to a File.
|
static File |
leftShift(File file,
InputStream data)
Append binary data to the file.
|
static File |
leftShift(File file,
Object text)
Write the text to the File.
|
static <K,V> Map<K,V> |
leftShift(Map<K,V> self,
Map.Entry<K,V> entry)
Overloads the left shift operator to provide an easy way to append
Map.Entry values to a Map.
|
static <K,V> Map<K,V> |
leftShift(Map<K,V> self,
Map<K,V> other)
Overloads the left shift operator to provide an easy way to put
one maps entries into another map.
|
static Number |
leftShift(Number self,
Number operand)
Implementation of the left shift operator for integral types.
|
static void |
leftShift(ObjectOutputStream self,
Object value)
Overloads the leftShift operator to add objects to an ObjectOutputStream.
|
static OutputStream |
leftShift(OutputStream self,
byte[] value)
Overloads the leftShift operator to provide an append mechanism to add bytes to a stream.
|
static OutputStream |
leftShift(OutputStream self,
InputStream in)
Pipe an InputStream into an OutputStream for efficient stream copying.
|
static Writer |
leftShift(OutputStream self,
Object value)
Overloads the leftShift operator to provide an append mechanism to add values to a stream.
|
static OutputStream |
leftShift(Socket self,
byte[] value)
Overloads the left shift operator to provide an append mechanism
to add bytes to the output stream of a socket
|
static Writer |
leftShift(Socket self,
Object value)
Overloads the left shift operator to provide an append mechanism to
add things to the output stream of a socket
|
static StringBuffer |
leftShift(StringBuffer self,
Object value)
Overloads the left shift operator to provide an easy way to append multiple
objects as string representations to a StringBuffer.
|
static StringBuilder |
leftShift(StringBuilder self,
Object value)
Overloads the left shift operator to provide syntactic sugar for appending to a StringBuilder.
|
static StringBuffer |
leftShift(String self,
Object value)
Overloads the left shift operator to provide an easy way to append multiple
objects as string representations to a String.
|
static Writer |
leftShift(Writer self,
Object value)
Overloads the left shift operator to provide a mechanism to append
values to a writer.
|
static boolean |
matches(CharSequence self,
Pattern pattern)
Tells whether or not a CharSequence matches the given
compiled regular expression Pattern.
|
static boolean |
matches(String self,
Pattern pattern)
Tells whether or not self matches the given
compiled regular expression Pattern.
|
static <T> T |
max(Collection<T> self)
Adds max() method to Collection objects.
|
static <T> T |
max(Collection<T> self,
Closure closure)
Selects an item in the collection having the maximum
value as determined by the supplied closure.
|
static <T> T |
max(Collection<T> self,
Comparator<T> comparator)
Selects the maximum value found in the collection using the given comparator.
|
static <T> T |
max(Iterator<T> self)
Adds max() method to Iterator objects.
|
static <T> T |
max(Iterator<T> self,
Closure closure)
Selects the maximum value found from the Iterator
using the closure to determine the correct ordering.
|
static <T> T |
max(Iterator<T> self,
Comparator<T> comparator)
Selects the maximum value found from the Iterator using the given comparator.
|
static <K,V> Map.Entry<K,V> |
max(Map<K,V> self,
Closure closure)
Selects an entry in the map having the maximum
calculated value as determined by the supplied closure.
|
static <T> T |
max(T[] self)
Adds max() method to Object arrays.
|
static <T> T |
max(T[] self,
Closure closure)
Selects the maximum value found from the Object array
using the closure to determine the correct ordering.
|
static <T> T |
max(T[] self,
Comparator<T> comparator)
Selects the maximum value found from the Object array using the given comparator.
|
static MetaClass |
metaClass(Class self,
Closure closure)
Sets/updates the metaclass for a given class to a closure.
|
static MetaClass |
metaClass(Object self,
Closure closure)
Sets/updates the metaclass for a given object to a closure.
|
static <T> T |
min(Collection<T> self)
Adds min() method to Collection objects.
|
static <T> T |
min(Collection<T> self,
Closure closure)
Selects an item in the collection having the minimum
value as determined by the supplied closure.
|
static <T> T |
min(Collection<T> self,
Comparator<T> comparator)
Selects the minimum value found in the collection using the given comparator.
|
static <T> T |
min(Iterator<T> self)
Adds min() method to Iterator objects.
|
static <T> T |
min(Iterator<T> self,
Closure closure)
Selects the minimum value found from the Iterator
using the closure to determine the correct ordering.
|
static <T> T |
min(Iterator<T> self,
Comparator<T> comparator)
Selects the minimum value found from the Iterator using the given comparator.
|
static <K,V> Map.Entry<K,V> |
min(Map<K,V> self,
Closure closure)
Selects an entry in the map having the minimum
calculated value as determined by the supplied closure.
|
static <T> T |
min(T[] self)
Adds min() method to Object arrays.
|
static <T> T |
min(T[] self,
Closure closure)
Selects the minimum value found from the Object array
using the closure to determine the correct ordering.
|
static <T> T |
min(T[] self,
Comparator<T> comparator)
Selects the minimum value found from the Object array using the given comparator.
|
static Number |
minus(Character left,
Character right)
Subtract one Character from another.
|
static Number |
minus(Character left,
Number right)
Subtract a Number from a Character.
|
static CharSequence |
minus(CharSequence self,
Object target)
Remove a part of a CharSequence by replacing the first occurrence
of target within self with '' and returns the result.
|
static <T> List<T> |
minus(List<T> self,
Collection<T> removeMe)
Create a List composed of the elements of the first list minus
every occurrence of elements of the given collection.
|
static <T> List<T> |
minus(List<T> self,
Object operand)
Create a new List composed of the elements of the first list minus every occurrence of the
operand.
|
static <K,V> Map<K,V> |
minus(Map<K,V> self,
Map<K,V> operands)
Create a Map composed of the entries of the first map minus the
entries of the given map.
|
static Number |
minus(Number left,
Character right)
Subtract a Character from a Number.
|
static <T> Set<T> |
minus(Set<T> self,
Collection operands)
Create a Set composed of the elements of the first set minus the
elements of the given collection.
|
static <T> Set<T> |
minus(Set<T> self,
Object operand)
Create a Set composed of the elements of the first set minus the operand.
|
static String |
minus(String self,
Object target)
Remove a part of a String.
|
static <T> T[] |
minus(T[] self,
Collection<T> removeMe)
Create an array composed of the elements of the first array minus the
elements of the given collection.
|
static <T> T[] |
minus(T[] self,
Object operand)
Create a new object array composed of the elements of the first array
minus the operand.
|
static <T> T[] |
minus(T[] self,
T[] removeMe)
Create an array composed of the elements of the first array minus the
elements of the given array.
|
static void |
mixin(Class self,
Class categoryClass)
Extend class globally with category methods.
|
static void |
mixin(Class self,
Class[] categoryClass)
Extend class globally with category methods.
|
static void |
mixin(Class self,
List<Class> categoryClasses)
Extend class globally with category methods.
|
static void |
mixin(MetaClass self,
Class categoryClass)
Extend class globally with category methods.
|
static void |
mixin(MetaClass self,
Class[] categoryClass)
Extend class globally with category methods.
|
static void |
mixin(MetaClass self,
List<Class> categoryClasses)
Extend object with category methods.
|
static Number |
mod(Number left,
Number right)
Performs a division modulus operation.
|
static Number |
multiply(BigDecimal left,
BigInteger right)
Multiply a BigDecimal and a BigInteger.
|
static Number |
multiply(BigDecimal left,
Double right)
Multiply a BigDecimal and a Double.
|
static Number |
multiply(Character left,
Character right)
Multiply two Characters.
|
static Number |
multiply(Character left,
Number right)
Multiply a Character by a Number.
|
static CharSequence |
multiply(CharSequence self,
Number factor)
Repeat a CharSequence a certain number of times.
|
static <T> List<T> |
multiply(Collection<T> self,
Number factor)
Create a List composed of the elements of this list, repeated
a certain number of times.
|
static Number |
multiply(Number left,
Character right)
Multiply a Number by a Character.
|
static String |
multiply(String self,
Number factor)
Repeat a String a certain number of times.
|
static DataInputStream |
newDataInputStream(File file)
Create a data input stream for this file
|
static DataOutputStream |
newDataOutputStream(File file)
Creates a new data output stream for this file.
|
static BufferedInputStream |
newInputStream(File file)
Creates a buffered input stream for this file.
|
static BufferedInputStream |
newInputStream(URL url)
Creates a buffered input stream for this URL.
|
static BufferedInputStream |
newInputStream(URL url,
Map parameters)
Creates a buffered input stream for this URL.
|
static <T> T |
newInstance(Class<T> c)
Convenience method to dynamically create a new instance of this
class.
|
static <T> T |
newInstance(Class<T> c,
Object[] args)
Helper to construct a new instance from the given arguments.
|
static ObjectInputStream |
newObjectInputStream(File file)
Create an object input stream for this file.
|
static ObjectInputStream |
newObjectInputStream(File file,
ClassLoader classLoader)
Create an object input stream for this file using the given class loader.
|
static ObjectInputStream |
newObjectInputStream(InputStream inputStream)
Create an object input stream for this input stream.
|
static ObjectInputStream |
newObjectInputStream(InputStream inputStream,
ClassLoader classLoader)
Create an object input stream for this input stream using the given class loader.
|
static ObjectOutputStream |
newObjectOutputStream(File file)
Create an object output stream for this file.
|
static ObjectOutputStream |
newObjectOutputStream(OutputStream outputStream)
Create an object output stream for this output stream.
|
static BufferedOutputStream |
newOutputStream(File file)
Create a buffered output stream for this file.
|
static PrintWriter |
newPrintWriter(File file)
Create a new PrintWriter for this file.
|
static PrintWriter |
newPrintWriter(File file,
String charset)
Create a new PrintWriter for this file, using specified
charset.
|
static PrintWriter |
newPrintWriter(Writer writer)
Create a new PrintWriter for this file, using specified
charset.
|
static BufferedReader |
newReader(File file)
Create a buffered reader for this file.
|
static BufferedReader |
newReader(File file,
String charset)
Create a buffered reader for this file, using the specified
charset as the encoding.
|
static BufferedReader |
newReader(InputStream self)
Creates a reader for this input stream.
|
static BufferedReader |
newReader(InputStream self,
String charset)
Creates a reader for this input stream, using the specified
charset as the encoding.
|
static BufferedReader |
newReader(URL url)
Creates a buffered reader for this URL.
|
static BufferedReader |
newReader(URL url,
Map parameters)
Creates a buffered reader for this URL.
|
static BufferedReader |
newReader(URL url,
Map parameters,
String charset)
Creates a buffered reader for this URL using the given encoding.
|
static BufferedReader |
newReader(URL url,
String charset)
Creates a buffered reader for this URL using the given encoding.
|
static BufferedWriter |
newWriter(File file)
Create a buffered writer for this file.
|
static BufferedWriter |
newWriter(File file,
boolean append)
Creates a buffered writer for this file, optionally appending to the
existing file content.
|
static BufferedWriter |
newWriter(File file,
String charset)
Creates a buffered writer for this file, writing data using the given
encoding.
|
static BufferedWriter |
newWriter(File file,
String charset,
boolean append)
Helper method to create a buffered writer for a file.
|
static Character |
next(Character self)
Increment a Character by one.
|
static CharSequence |
next(CharSequence self)
This method is called by the ++ operator for the class CharSequence.
|
static Number |
next(Number self)
Increment a Number by one.
|
static String |
next(String self)
This method is called by the ++ operator for the class String.
|
static CharSequence |
normalize(CharSequence self)
Return a CharSequence with linefeeds and carriage returns normalized to linefeeds.
|
static String |
normalize(String self)
Return a String with linefeeds and carriage returns normalized to linefeeds.
|
static int |
numberAwareCompareTo(Comparable self,
Comparable other)
Provides a method that compares two comparables using Groovy's
default number aware comparator.
|
static BitSet |
or(BitSet left,
BitSet right)
Bitwise OR together two BitSets.
|
static Boolean |
or(Boolean left,
Boolean right)
Logical disjunction of two boolean operators
|
static Number |
or(Number left,
Number right)
Bitwise OR together two numbers.
|
static CharSequence |
padLeft(CharSequence self,
Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed.
|
static CharSequence |
padLeft(CharSequence self,
Number numberOfChars,
CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the left.
|
static String |
padLeft(String self,
Number numberOfChars)
Pad a String to a minimum length specified by numberOfChars by adding the space character to the left as many times as needed.
|
static String |
padLeft(String self,
Number numberOfChars,
String padding)
Pad a String to a minimum length specified by numberOfChars, adding the supplied padding String as many times as needed to the left.
|
static CharSequence |
padRight(CharSequence self,
Number numberOfChars)
Pad a CharSequence to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed.
|
static CharSequence |
padRight(CharSequence self,
Number numberOfChars,
CharSequence padding)
Pad a CharSequence to a minimum length specified by numberOfChars, adding the supplied padding CharSequence as many times as needed to the right.
|
static String |
padRight(String self,
Number numberOfChars)
Pad a String to a minimum length specified by numberOfChars by adding the space character to the right as many times as needed.
|
static String |
padRight(String self,
Number numberOfChars,
String padding)
Pad a String to a minimum length specified by numberOfChars, adding the supplied padding String as many times as needed to the right.
|
static <T> Set<List<T>> |
permutations(List<T> self)
Finds all permutations of a collection.
|
static Number |
plus(Character left,
Character right)
Add one Character to another.
|
static Number |
plus(Character left,
Number right)
Add a Character and a Number.
|
static CharSequence |
plus(CharSequence left,
Object value)
Appends the String representation of the given operand to this string.
|
static <T> Collection<T> |
plus(Collection<T> left,
Collection<T> right)
Create a Collection as a union of two collections.
|
static <T> Collection<T> |
plus(Collection<T> left,
T right)
Create a collection as a union of a Collection and an Object.
|
static <T> List<T> |
plus(List<T> self,
int index,
List<T> additions)
Creates a new list by adding all of the elements in the specified list
to the elements from this list at the specified index.
|
static <T> List<T> |
plus(List<T> self,
int index,
T[] items)
Creates a new list by adding all of the elements in the specified array to the elements from the original list at the specified index.
|
static <K,V> Map<K,V> |
plus(Map<K,V> self,
Collection<Map.Entry<K,V>> entries)
Returns a new
Map containing all entries from self and entries ,
giving precedence to entries . |
static <K,V> Map<K,V> |
plus(Map<K,V> left,
Map<K,V> right)
Returns a new
Map containing all entries from left and right ,
giving precedence to right . |
static Number |
plus(Number left,
Character right)
Add a Number and a Character.
|
static String |
plus(Number value,
String right)
Appends a String to the string representation of this number.
|
static String |
plus(StringBuffer left,
String value)
Appends a String to this StringBuffer.
|
static String |
plus(String left,
Object value)
Appends the String representation of the given operand to this string.
|
static <T> T |
pop(List<T> self)
Removes the last item from the List.
|
static Number |
power(BigDecimal self,
Integer exponent)
Power of a BigDecimal to an integer certain exponent.
|
static Number |
power(BigInteger self,
Integer exponent)
Power of a BigInteger to an integer certain exponent.
|
static Number |
power(Integer self,
Integer exponent)
Power of an integer to an integer certain exponent.
|
static Number |
power(Long self,
Integer exponent)
Power of a long to an integer certain exponent.
|
static Number |
power(Number self,
Number exponent)
Power of a Number to a certain exponent.
|
static Character |
previous(Character self)
Decrement a Character by one.
|
static CharSequence |
previous(CharSequence self)
This method is called by the -- operator for the class CharSequence.
|
static Number |
previous(Number self)
Decrement a Number by one.
|
static String |
previous(String self)
This method is called by the -- operator for the class String.
|
protected static List |
primitiveArrayGet(Object self,
Collection indices)
Implements the getAt(Collection) method for primitive type arrays.
|
protected static Object |
primitiveArrayGet(Object self,
int idx)
Implements the getAt(int) method for primitive type arrays.
|
protected static List |
primitiveArrayGet(Object self,
Range range)
Implements the getAt(Range) method for primitive type arrays.
|
protected static Object |
primitiveArrayPut(Object self,
int idx,
Object newValue)
Implements the setAt(int idx) method for primitive type arrays.
|
static void |
print(Closure self,
Object value)
Print a value to the standard output stream.
|
static void |
print(Object self,
Object value)
Print a value formatted Groovy style to self if it
is a Writer, otherwise to the standard output stream.
|
static void |
print(Object self,
PrintWriter out)
Print to a console in interactive format.
|
static void |
print(PrintStream self,
Object value)
Print a value formatted Groovy style to the print stream.
|
static void |
print(PrintWriter self,
Object value)
Print a value formatted Groovy style to the print writer.
|
static void |
printf(Object self,
String format,
Object arg)
Prints a formatted string using the specified format string and
arguments.
|
static void |
printf(Object self,
String format,
Object[] values)
Printf to a console (Only works with JDK1.5 or later).
|
static void |
println(Closure self)
Print a linebreak to the standard output stream.
|
static void |
println(Closure self,
Object value)
Print a value (followed by a newline) to the standard output stream.
|
static void |
println(Object self)
Print a linebreak to the standard output stream.
|
static void |
println(Object self,
Object value)
Print a value formatted Groovy style (followed by a newline) to self
if it is a Writer, otherwise to the standard output stream.
|
static void |
println(Object self,
PrintWriter out)
Print to a console in interactive format.
|
static void |
println(PrintStream self,
Object value)
Print a value formatted Groovy style (followed by a newline) to the print stream.
|
static void |
println(PrintWriter self,
Object value)
Print a value formatted Groovy style (followed by a newline) to the print writer.
|
static <T> boolean |
push(List<T> self,
T value)
Appends an item to the List.
|
static <K,V> Map<K,V> |
putAll(Map<K,V> self,
Collection<Map.Entry<K,V>> entries)
Provides an easy way to append multiple Map.Entry values to a Map.
|
static void |
putAt(BitSet self,
int index,
boolean value)
Support subscript-style assignment for a BitSet.
|
static void |
putAt(BitSet self,
IntRange range,
boolean value)
Support assigning a range of values with a single assignment statement.
|
static <T> void |
putAt(List<T> self,
int idx,
T value)
A helper method to allow lists to work with subscript operators.
|
static void |
putAt(List self,
EmptyRange range,
Collection value)
A helper method to allow lists to work with subscript operators.
|
static void |
putAt(List self,
EmptyRange range,
Object value)
A helper method to allow lists to work with subscript operators.
|
static void |
putAt(List self,
IntRange range,
Collection col)
List subscript assignment operator when given a range as the index and
the assignment operand is a collection.
|
static void |
putAt(List self,
IntRange range,
Object value)
List subscript assignment operator when given a range as the index.
|
static void |
putAt(List self,
List splice,
List values)
A helper method to allow lists to work with subscript operators.
|
static void |
putAt(List self,
List splice,
Object value)
A helper method to allow lists to work with subscript operators.
|
static <K,V> V |
putAt(Map<K,V> self,
K key,
V value)
A helper method to allow maps to work with subscript operators
|
static void |
putAt(Object self,
String property,
Object newValue)
Allows the subscript operator to be used to set dynamically named property values.
|
static void |
putAt(StringBuffer self,
EmptyRange range,
Object value)
Support the range subscript operator for StringBuffer.
|
static void |
putAt(StringBuffer self,
IntRange range,
Object value)
Support the range subscript operator for StringBuffer.
|
static byte[] |
readBytes(File file)
Reads the content of the file into a byte array.
|
static String |
readLine(Reader self)
Read a single, whole line from the given Reader.
|
static List<CharSequence> |
readLines(CharSequence self)
Return the lines of a CharSequence as a List of CharSequence.
|
static List<String> |
readLines(File file)
Reads the file into a list of Strings, with one item for each line.
|
static List<String> |
readLines(File file,
String charset)
Reads the file into a list of Strings, with one item for each line.
|
static List<String> |
readLines(InputStream stream)
Reads the stream into a list, with one element for each line.
|
static List<String> |
readLines(InputStream stream,
String charset)
Reads the stream into a list, with one element for each line.
|
static List<String> |
readLines(Reader reader)
Reads the reader into a list of Strings, with one entry for each line.
|
static List<String> |
readLines(String self)
Return the lines of a String as a List of Strings.
|
static List<String> |
readLines(URL self)
Reads the URL contents into a list, with one element for each line.
|
static List<String> |
readLines(URL self,
String charset)
Reads the URL contents into a list, with one element for each line.
|
static boolean |
removeAll(Collection self,
Closure condition)
Modifies this collection by removing the elements that are matched according
to the specified closure condition.
|
static boolean |
removeAll(Collection self,
Object[] items)
Modifies this collection by removing its elements that are contained
within the specified object array.
|
static boolean |
renameTo(File self,
String newPathName)
Renames the file.
|
static CharSequence |
replaceAll(CharSequence self,
CharSequence regex,
CharSequence replacement)
Replaces each substring of this CharSequence that matches the given
regular expression with the given replacement.
|
static CharSequence |
replaceAll(CharSequence self,
CharSequence regex,
Closure closure)
Replaces all occurrences of a captured group by the result of a closure on that text.
|
static CharSequence |
replaceAll(CharSequence self,
Pattern pattern,
CharSequence replacement)
Replaces all substrings of a CharSequence that match the given
compiled regular expression with the given replacement.
|
static String |
replaceAll(CharSequence self,
Pattern pattern,
Closure closure)
Replaces all occurrences of a captured group by the result of a closure call on that text.
|
static String |
replaceAll(String self,
Pattern pattern,
Closure closure)
Replaces all occurrences of a captured group by the result of a closure call on that text.
|
static String |
replaceAll(String self,
Pattern pattern,
String replacement)
Replaces all substrings of a String that match the given
compiled regular expression with the given replacement.
|
static String |
replaceAll(String self,
String regex,
Closure closure)
Replaces all occurrences of a captured group by the result of a closure on that text.
|
static String |
replaceFirst(CharSequence self,
CharSequence regex,
CharSequence replacement)
Replaces the first substring of this CharSequence that matches the given
regular expression with the given replacement.
|
static String |
replaceFirst(CharSequence self,
CharSequence regex,
Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text.
|
static CharSequence |
replaceFirst(CharSequence self,
Pattern pattern,
CharSequence replacement)
Replaces the first substring of a CharSequence that matches the given
compiled regular expression with the given replacement.
|
static String |
replaceFirst(CharSequence self,
Pattern pattern,
Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text.
|
static String |
replaceFirst(String self,
Pattern pattern,
Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text.
|
static String |
replaceFirst(String self,
Pattern pattern,
String replacement)
Replaces the first substring of a String that matches the given
compiled regular expression with the given replacement.
|
static String |
replaceFirst(String self,
String regex,
Closure closure)
Replaces the first occurrence of a captured group by the result of a closure call on that text.
|
static List<MetaMethod> |
respondsTo(Object self,
String name)
Returns an object satisfying Groovy truth if the implementing MetaClass responds to
a method with the given name regardless of the arguments.
|
static List<MetaMethod> |
respondsTo(Object self,
String name,
Object[] argTypes)
Returns an object satisfying Groovy truth if the implementing MetaClass responds to
a method with the given name and arguments types.
|
static boolean |
retainAll(Collection self,
Closure condition)
Modifies this collection so that it retains only its elements
that are matched according to the specified closure condition.
|
static boolean |
retainAll(Collection self,
Object[] items)
Modifies this collection so that it retains only its elements that are contained
in the specified array.
|
static CharSequence |
reverse(CharSequence self)
Creates a new CharSequence which is the reverse (backwards) of this string
|
static <T> Iterator<T> |
reverse(Iterator<T> self)
Reverses the iterator.
|
static <T> List<T> |
reverse(List<T> self)
Creates a new List with the identical contents to this list
but in reverse order.
|
static <T> List<T> |
reverse(List<T> self,
boolean mutate)
Reverses the elements in a list.
|
static String |
reverse(String self)
Creates a new string which is the reverse (backwards) of this string
|
static <T> T[] |
reverse(T[] self)
Creates a new array containing items which are the same as this array but in reverse order.
|
static <T> T[] |
reverse(T[] self,
boolean mutate)
Reverse the items in an array.
|
static <T> List<T> |
reverseEach(List<T> self,
Closure closure)
Iterate over each element of the list in the reverse order.
|
static <K,V> Map<K,V> |
reverseEach(Map<K,V> self,
Closure closure)
Allows a Map to be iterated through in reverse order using a closure.
|
static <T> T[] |
reverseEach(T[] self,
Closure closure)
Iterate over each element of the array in the reverse order.
|
static Number |
rightShift(Number self,
Number operand)
Implementation of the right shift operator for integral types.
|
static Number |
rightShiftUnsigned(Number self,
Number operand)
Implementation of the right shift (unsigned) operator for integral types.
|
static long |
round(Double number)
Round the value
|
static double |
round(Double number,
int precision)
Round the value
|
static int |
round(Float number)
Round the value
|
static float |
round(Float number,
int precision)
Round the value
|
static TimerTask |
runAfter(Timer timer,
int delay,
Closure closure)
Allows a simple syntax for using timers.
|
static void |
setBytes(File file,
byte[] bytes)
Write the bytes from the byte array to the File.
|
static void |
setBytes(OutputStream os,
byte[] bytes)
Write the byte[] to the output stream.
|
static void |
setIndex(Matcher matcher,
int idx)
Set the position of the given Matcher to the given index.
|
static void |
setMetaClass(Class self,
MetaClass metaClass)
Sets the metaclass for a given class.
|
static void |
setMetaClass(Object self,
MetaClass metaClass)
Set the metaclass for an object
|
static void |
setText(File file,
String text)
Synonym for write(text) allowing file.text = 'foo'.
|
static void |
setText(File file,
String text,
String charset)
Synonym for write(text, charset) allowing:
myFile.setText('some text', charset)
or with some help from
ExpandoMetaClass , you could do something like:
myFile.metaClass.setText = { String s -> delegate.setText(s, 'UTF-8') }
myfile.text = 'some text'
|
static int |
size(boolean[] array)
Allows arrays to behave similar to collections.
|
static int |
size(byte[] array)
Allows arrays to behave similar to collections.
|
static int |
size(char[] array)
Allows arrays to behave similar to collections.
|
static int |
size(CharSequence text)
Provide the standard Groovy
size() method for CharSequence . |
static int |
size(double[] array)
Allows arrays to behave similar to collections.
|
static long |
size(File self)
Provide the standard Groovy
size() method for File . |
static int |
size(float[] array)
Allows arrays to behave similar to collections.
|
static int |
size(int[] array)
Allows arrays to behave similar to collections.
|
static int |
size(Iterator self)
Provide the standard Groovy
size() method for Iterator . |
static int |
size(long[] array)
Allows arrays to behave similar to collections.
|
static long |
size(Matcher self)
Provide the standard Groovy
size() method for Matcher . |
static int |
size(Object[] self)
Provide the standard Groovy
size() method for an array. |
static int |
size(short[] array)
Allows arrays to behave similar to collections.
|
static int |
size(String text)
Provide the standard Groovy
size() method for String . |
static int |
size(StringBuffer buffer)
Provide the standard Groovy
size() method for StringBuffer . |
static <T> List<T> |
sort(Collection<T> self)
Sorts the Collection.
|
static <T> List<T> |
sort(Collection<T> self,
boolean mutate)
Sorts the Collection.
|
static <T> List<T> |
sort(Collection<T> self,
boolean mutate,
Closure closure)
Sorts this Collection using the given Closure to determine the correct ordering.
|
static <T> List<T> |
sort(Collection<T> self,
boolean mutate,
Comparator<T> comparator)
Sorts the Collection using the given Comparator.
|
static <T> List<T> |
sort(Collection<T> self,
Closure closure)
Sorts this Collection using the given Closure to determine the correct ordering.
|
static <T> List<T> |
sort(Collection<T> self,
Comparator<T> comparator)
Sorts the Collection using the given Comparator.
|
static <T> Iterator<T> |
sort(Iterator<T> self)
Sorts the given iterator items into a sorted iterator.
|
static <T> Iterator<T> |
sort(Iterator<T> self,
Closure closure)
Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering.
|
static <T> Iterator<T> |
sort(Iterator<T> self,
Comparator<T> comparator)
Sorts the given iterator items into a sorted iterator using the comparator.
|
static <K,V> Map<K,V> |
sort(Map<K,V> self)
Sorts the elements from the given map into a new ordered Map using
the natural ordering of the keys to determine the ordering.
|
static <K,V> Map<K,V> |
sort(Map<K,V> self,
Closure closure)
Sorts the elements from the given map into a new ordered map using
the closure as a comparator to determine the ordering.
|
static <K,V> Map<K,V> |
sort(Map<K,V> self,
Comparator<K> comparator)
Sorts the elements from the given map into a new ordered Map using
the specified key comparator to determine the ordering.
|
static <K,V> SortedMap<K,V> |
sort(SortedMap<K,V> self)
Avoids doing unnecessary work when sorting an already sorted map (i.e. an identity function for an already sorted map).
|
static <T> SortedSet<T> |
sort(SortedSet<T> self)
Avoids doing unnecessary work when sorting an already sorted set (i.e. an identity function for an already sorted set).
|
static <T> T[] |
sort(T[] self)
Modifies this array so that its elements are in sorted order.
|
static <T> T[] |
sort(T[] self,
boolean mutate)
Sorts the given array into sorted order.
|
static <T> T[] |
sort(T[] self,
boolean mutate,
Closure closure)
Modifies this array so that its elements are in sorted order using the Closure to determine the correct ordering.
|
static <T> T[] |
sort(T[] self,
boolean mutate,
Comparator<T> comparator)
Modifies this array so that its elements are in sorted order as determined by the given comparator.
|
static <T> T[] |
sort(T[] self,
Closure closure)
Sorts the elements from this array into a newly created array using
the Closure to determine the correct ordering.
|
static <T> T[] |
sort(T[] self,
Comparator<T> comparator)
Sorts the given array into sorted order using the given comparator.
|
static CharSequence[] |
split(CharSequence self)
Convenience method to split a CharSequence (with whitespace as delimiter).
|
static <T> Collection<Collection<T>> |
split(Collection<T> self,
Closure closure)
Splits all items into two collections based on the closure condition.
|
static String[] |
split(GString self)
Convenience method to split a GString (with whitespace as delimiter).
|
static Collection |
split(Object self,
Closure closure)
Splits all items into two lists based on the closure condition.
|
static String[] |
split(String self)
Convenience method to split a string (with whitespace as delimiter)
Like tokenize, but returns an Array of Strings instead of a List
|
static <T> T |
splitEachLine(CharSequence self,
CharSequence regex,
Closure<T> closure)
Iterates through the given CharSequence line by line, splitting each line using
the given separator.
|
static <T> T |
splitEachLine(CharSequence self,
Pattern pattern,
Closure<T> closure)
Iterates through the given CharSequence line by line, splitting each line using
the given separator Pattern.
|
static <T> T |
splitEachLine(File self,
Pattern pattern,
Closure<T> closure)
Iterates through this file line by line, splitting each line using
the given separator Pattern.
|
static <T> T |
splitEachLine(File self,
Pattern pattern,
String charset,
Closure<T> closure)
Iterates through this file line by line, splitting each line using
the given regex separator Pattern.
|
static <T> T |
splitEachLine(File self,
String regex,
Closure<T> closure)
Iterates through this file line by line, splitting each line using
the given regex separator.
|
static <T> T |
splitEachLine(File self,
String regex,
String charset,
Closure<T> closure)
Iterates through this file line by line, splitting each line using
the given regex separator.
|
static <T> T |
splitEachLine(InputStream stream,
Pattern pattern,
Closure<T> closure)
Iterates through the given InputStream line by line, splitting each line using
the given separator Pattern.
|
static <T> T |
splitEachLine(InputStream stream,
Pattern pattern,
String charset,
Closure<T> closure)
Iterates through the given InputStream line by line using the specified
encoding, splitting each line using the given separator Pattern.
|
static <T> T |
splitEachLine(InputStream stream,
String regex,
Closure<T> closure)
Iterates through the given InputStream line by line, splitting each line using
the given separator.
|
static <T> T |
splitEachLine(InputStream stream,
String regex,
String charset,
Closure<T> closure)
Iterates through the given InputStream line by line using the specified
encoding, splitting each line using the given separator.
|
static <T> T |
splitEachLine(Reader self,
Pattern pattern,
Closure<T> closure)
Iterates through the given reader line by line, splitting each line using
the given regex separator Pattern.
|
static <T> T |
splitEachLine(Reader self,
String regex,
Closure<T> closure)
Iterates through the given reader line by line, splitting each line using
the given regex separator.
|
static <T> T |
splitEachLine(String self,
Pattern pattern,
Closure<T> closure)
Iterates through the given String line by line, splitting each line using
the given separator Pattern.
|
static <T> T |
splitEachLine(String self,
String regex,
Closure<T> closure)
Iterates through the given String line by line, splitting each line using
the given separator.
|
static <T> T |
splitEachLine(URL self,
Pattern pattern,
Closure<T> closure)
Iterates through the input stream associated with this URL line by line, splitting each line using
the given regex separator Pattern.
|
static <T> T |
splitEachLine(URL self,
Pattern pattern,
String charset,
Closure<T> closure)
Iterates through the input stream associated with this URL line by line, splitting each line using
the given regex separator Pattern.
|
static <T> T |
splitEachLine(URL self,
String regex,
Closure<T> closure)
Iterates through the input stream associated with this URL line by line, splitting each line using
the given regex separator.
|
static <T> T |
splitEachLine(URL self,
String regex,
String charset,
Closure<T> closure)
Iterates through the input stream associated with this URL line by line, splitting each line using
the given regex separator.
|
static SpreadMap |
spread(Map self)
Synonym for
toSpreadMap(java.util.Map) . |
static String |
sprintf(Object self,
String format,
Object arg)
Returns a formatted string using the specified format string and
arguments.
|
static String |
sprintf(Object self,
String format,
Object[] values)
Sprintf to a string (Only works with JDK1.5 or later).
|
static void |
step(Number self,
Number to,
Number stepNumber,
Closure closure)
Iterates from this number up to the given number using a step increment.
|
static CharSequence |
stripIndent(CharSequence self)
Strip leading spaces from every line in a CharSequence.
|
static CharSequence |
stripIndent(CharSequence self,
int numChars)
Strip numChar leading characters from
every line in a CharSequence.
|
static String |
stripIndent(String self)
Strip leading spaces from every line in a String.
|
static String |
stripIndent(String self,
int numChars)
Strip numChar leading characters from
every line in a String.
|
static CharSequence |
stripMargin(CharSequence self)
Strip leading whitespace/control characters followed by '|' from
every line in a CharSequence.
|
static CharSequence |
stripMargin(CharSequence self,
char marginChar)
Strip leading whitespace/control characters followed by marginChar from
every line in a String.
|
static String |
stripMargin(CharSequence self,
CharSequence marginChar)
Strip leading whitespace/control characters followed by marginChar from
every line in a CharSequence.
|
static String |
stripMargin(String self)
Strip leading whitespace/control characters followed by '|' from
every line in a String.
|
static String |
stripMargin(String self,
char marginChar)
Strip leading whitespace/control characters followed by marginChar from
every line in a String.
|
static String |
stripMargin(String self,
String marginChar)
Strip leading whitespace/control characters followed by marginChar from
every line in a String.
|
static <K,V> Map<K,V> |
subMap(Map<K,V> map,
Collection<K> keys)
Creates a sub-Map containing the given keys.
|
static <T> Set<List<T>> |
subsequences(List<T> self)
Finds all non-null subsequences of a list.
|
static Object |
sum(Collection self)
Sums the items in a collection.
|
static Object |
sum(Collection self,
Closure closure)
Sums the result of apply a closure to each item of a collection.
|
static Object |
sum(Collection self,
Object initialValue)
Sums the items in a collection, adding the result to some initial value.
|
static Object |
sum(Collection self,
Object initialValue,
Closure closure)
Sums the result of applying a closure to each item of a collection to some initial value.
|
static Object |
sum(Iterator<Object> self)
Sums the items from an Iterator.
|
static Object |
sum(Iterator<Object> self,
Closure closure)
Sums the result of apply a closure to each item returned from an iterator.
|
static Object |
sum(Iterator<Object> self,
Object initialValue)
Sums the items from an Iterator, adding the result to some initial value.
|
static Object |
sum(Iterator<Object> self,
Object initialValue,
Closure closure)
Sums the result of applying a closure to each item of an Iterator to some initial value.
|
static Object |
sum(Object[] self)
Sums the items in an array.
|
static Object |
sum(Object[] self,
Closure closure)
Sums the result of apply a closure to each item of an array.
|
static Object |
sum(Object[] self,
Object initialValue)
Sums the items in an array, adding the result to some initial value.
|
static Object |
sum(Object[] self,
Object initialValue,
Closure closure)
Sums the result of applying a closure to each item of an array to some initial value.
|
static <T> List<T> |
tail(List<T> self)
Returns the items from the List excluding the first item.
|
static <T> T[] |
tail(T[] self)
Returns the items from the Object array excluding the first item.
|
static CharSequence |
take(CharSequence self,
int num)
Returns the first
num elements from this CharSequence. |
static <T> Iterator<T> |
take(Iterator<T> self,
int num)
Returns an iterator to up to the first
num elements from this iterator. |
static <T> List<T> |
take(List<T> self,
int num)
Returns the first
num elements from the head of this list. |
static <K,V> Map<K,V> |
take(Map<K,V> self,
int num)
Returns a new map containing the first
num elements from the head of this map. |
static <T> T[] |
take(T[] self,
int num)
Returns the first
num elements from the head of this array. |
static void |
times(Number self,
Closure closure)
Executes the closure this many times, starting from zero.
|
static String |
toArrayString(Object[] self)
Returns the string representation of the given array.
|
static BigDecimal |
toBigDecimal(CharSequence self)
Parse a CharSequence into a BigDecimal
|
static BigDecimal |
toBigDecimal(Number self)
Transform a Number into a BigDecimal
|
static BigDecimal |
toBigDecimal(String self)
Parse a String into a BigDecimal
|
static BigInteger |
toBigInteger(CharSequence self)
Parse a CharSequence into a BigInteger
|
static BigInteger |
toBigInteger(Number self)
Transform this Number into a BigInteger.
|
static BigInteger |
toBigInteger(String self)
Parse a String into a BigInteger
|
static Boolean |
toBoolean(Boolean self)
Identity conversion which returns Boolean.TRUE for a true Boolean and Boolean.FALSE for a false Boolean.
|
static Boolean |
toBoolean(String self)
Converts the given string into a Boolean object.
|
static Character |
toCharacter(String self)
Converts the given string into a Character object
using the first character in the string.
|
static Double |
toDouble(CharSequence self)
Parse a CharSequence into a Double
|
static Double |
toDouble(Number self)
Transform a Number into a Double
|
static Double |
toDouble(String self)
Parse a String into a Double
|
static Float |
toFloat(CharSequence self)
Parse a CharSequence into a Float
|
static Float |
toFloat(Number self)
Transform a Number into a Float
|
static Float |
toFloat(String self)
Parse a String into a Float
|
static Integer |
toInteger(CharSequence self)
Parse a CharSequence into an Integer
|
static Integer |
toInteger(Number self)
Transform a Number into an Integer
|
static Integer |
toInteger(String self)
Parse a String into an Integer
|
static List<CharSequence> |
tokenize(CharSequence self)
Tokenize a CharSequence (with a whitespace as the delimiter).
|
static List<CharSequence> |
tokenize(CharSequence self,
Character token)
Tokenize a CharSequence based on the given character delimiter.
|
static List<CharSequence> |
tokenize(CharSequence self,
CharSequence token)
Tokenize a CharSequence based on the given CharSequence delimiter.
|
static List<String> |
tokenize(String self)
Tokenize a String (with a whitespace as the delimiter).
|
static List<String> |
tokenize(String self,
Character token)
Tokenize a String based on the given character delimiter.
|
static List<String> |
tokenize(String self,
String token)
Tokenize a String based on the given string delimiter.
|
static List<Boolean> |
toList(boolean[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<Byte> |
toList(byte[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<Character> |
toList(char[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<CharSequence> |
toList(CharSequence self)
Converts the given CharSequence into a List of CharSequence of one character.
|
static <T> List<T> |
toList(Collection<T> self)
Convert a Collection to a List.
|
static List<Double> |
toList(double[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static <T> List<T> |
toList(Enumeration<T> self)
Convert an enumeration to a List.
|
static List<Float> |
toList(float[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<Integer> |
toList(int[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static <T> List<T> |
toList(Iterator<T> self)
Convert an iterator to a List.
|
static List<Long> |
toList(long[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<Short> |
toList(short[] array)
Converts this array to a List of the same size, with each element
added to the list.
|
static List<String> |
toList(String self)
Converts the given String into a List of strings of one character.
|
static <T> List<T> |
toList(T[] array)
Allows conversion of arrays into a mutable List.
|
static String |
toListString(Collection self)
Returns the string representation of the given list.
|
static String |
toListString(Collection self,
int maxSize)
Returns the string representation of the given list.
|
static Long |
toLong(CharSequence self)
Parse a CharSequence into a Long
|
static Long |
toLong(Number self)
Transform a Number into a Long
|
static Long |
toLong(String self)
Parse a String into a Long
|
static char |
toLowerCase(Character self)
Converts the character to lowercase.
|
static String |
toMapString(Map self)
Returns the string representation of this map.
|
static String |
toMapString(Map self,
int maxSize)
Returns the string representation of this map.
|
static Set<Boolean> |
toSet(boolean[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<Byte> |
toSet(byte[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<Character> |
toSet(char[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<CharSequence> |
toSet(CharSequence self)
Converts the given CharSequence into a Set of unique CharSequence of one character.
|
static <T> Set<T> |
toSet(Collection<T> self)
Convert a Collection to a Set.
|
static Set<Double> |
toSet(double[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static <T> Set<T> |
toSet(Enumeration<T> self)
Convert an enumeration to a Set.
|
static Set<Float> |
toSet(float[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<Integer> |
toSet(int[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static <T> Set<T> |
toSet(Iterator<T> self)
Convert an iterator to a Set.
|
static Set<Long> |
toSet(long[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<Short> |
toSet(short[] array)
Converts this array to a Set, with each unique element
added to the set.
|
static Set<String> |
toSet(String self)
Converts the given String into a Set of unique strings of one character.
|
static Short |
toShort(CharSequence self)
Parse a CharSequence into a Short
|
static Short |
toShort(String self)
Parse a String into a Short
|
static SpreadMap |
toSpreadMap(List self)
Creates a spreadable map from this list.
|
static SpreadMap |
toSpreadMap(Map self)
Returns a new
SpreadMap from this map. |
static SpreadMap |
toSpreadMap(Object[] self)
Creates a spreadable map from this array.
|
static String |
toString(AbstractCollection self)
Returns the string representation of the given collection.
|
static String |
toString(AbstractMap self)
Returns the string representation of the given map.
|
static String |
toString(boolean[] self)
Returns the string representation of the given array.
|
static String |
toString(byte[] self)
Returns the string representation of the given array.
|
static String |
toString(char[] self)
Returns the string representation of the given array.
|
static String |
toString(double[] self)
Returns the string representation of the given array.
|
static String |
toString(float[] self)
Returns the string representation of the given array.
|
static String |
toString(int[] self)
Returns the string representation of the given array.
|
static String |
toString(long[] self)
Returns the string representation of the given array.
|
static String |
toString(Object value)
Create a String representation of this object.
|
static String |
toString(Object[] self)
Returns the string representation of this array's contents.
|
static String |
toString(short[] self)
Returns the string representation of the given array.
|
static char |
toUpperCase(Character self)
Converts the character to uppercase.
|
static URI |
toURI(CharSequence self)
Transforms a CharSequence representing a URI into a URI object.
|
static URI |
toURI(String self)
Transforms a String representing a URI into a URI object.
|
static URL |
toURL(CharSequence self)
Transforms a CharSequence representing a URL into a URL object.
|
static URL |
toURL(String self)
Transforms a String representing a URL into a URL object.
|
static CharSequence |
tr(CharSequence self,
CharSequence sourceSet,
CharSequence replacementSet)
Translates a string by replacing characters from the sourceSet with characters from replacementSet.
|
static String |
tr(String self,
String sourceSet,
String replacementSet)
Translates a string by replacing characters from the sourceSet with characters from replacementSet.
|
static void |
transformChar(Reader self,
Writer writer,
Closure closure)
Transforms each character from this reader by passing it to the given
closure.
|
static void |
transformLine(Reader reader,
Writer writer,
Closure closure)
Transforms the lines from a reader with a Closure and
write them to a writer.
|
static List |
transpose(List self)
Adds GroovyCollections#transpose(List) as a method on lists.
|
static void |
traverse(File self,
Closure closure)
Invokes the closure for each descendant file in this directory tree.
|
static void |
traverse(File self,
Map<String,Object> options)
Invokes the closure specified with key 'visit' in the options Map
for each descendant file in this directory tree.
|
static void |
traverse(File self,
Map<String,Object> options,
Closure closure)
Invokes
closure for each descendant file in this directory tree. |
static double |
trunc(Double number)
Truncate the value
|
static double |
trunc(Double number,
int precision)
Truncate the value
|
static float |
trunc(Float number)
Truncate the value
|
static float |
trunc(Float number,
int precision)
Truncate the value
|
static Number |
unaryMinus(Number left)
Negates the number.
|
static CharSequence |
unexpand(CharSequence self)
Replaces sequences of whitespaces with tabs using tabStops of size 8.
|
static CharSequence |
unexpand(CharSequence self,
int tabStop)
Replaces sequences of whitespaces with tabs.
|
static String |
unexpand(String self)
Replaces sequences of whitespaces with tabs using tabStops of size 8.
|
static String |
unexpand(String self,
int tabStop)
Replaces sequences of whitespaces with tabs.
|
static CharSequence |
unexpandLine(CharSequence self,
int tabStop)
Replaces sequences of whitespaces with tabs within a line.
|
static String |
unexpandLine(String self,
int tabStop)
Replaces sequences of whitespaces with tabs within a line.
|
static <T> Collection<T> |
unique(Collection<T> self)
Modifies this collection to remove all duplicated items, using the
default comparator.
|
static <T> Collection<T> |
unique(Collection<T> self,
boolean mutate)
Remove all duplicates from a given Collection using the default comparator.
|
static <T> Collection<T> |
unique(Collection<T> self,
boolean mutate,
Closure closure)
A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
|
static <T> Collection<T> |
unique(Collection<T> self,
boolean mutate,
Comparator<T> comparator)
Remove all duplicates from a given Collection.
|
static <T> Collection<T> |
unique(Collection<T> self,
Closure closure)
A convenience method for making a collection unique using a Closure
to determine duplicate (equal) items.
|
static <T> Collection<T> |
unique(Collection<T> self,
Comparator<T> comparator)
Remove all duplicates from a given Collection.
|
static <T> Iterator<T> |
unique(Iterator<T> self)
Returns an iterator equivalent to this iterator all duplicated items removed
by using the default comparator.
|
static <T> Iterator<T> |
unique(Iterator<T> self,
Closure closure)
Returns an iterator equivalent to this iterator but with all duplicated items
removed by using a Closure to determine duplicate (equal) items.
|
static <T> Iterator<T> |
unique(Iterator<T> self,
Comparator<T> comparator)
Returns an iterator equivalent to this iterator with all duplicated
items removed by using the supplied comparator.
|
static void |
upto(BigDecimal self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(BigInteger self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(double self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(Double self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(float self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(Float self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(long self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(Long self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static void |
upto(Number self,
Number to,
Closure closure)
Iterates from this number up to the given number, inclusive,
incrementing by one each time.
|
static <T> T |
use(Object self,
Class categoryClass,
Closure<T> closure)
Scoped use method
|
static <T> T |
use(Object self,
List<Class> categoryClassList,
Closure<T> closure)
Scoped use method with list of categories.
|
static Object |
use(Object self,
Object[] array)
Allows you to use a list of categories, specifying the list as varargs.
|
static <T> T |
with(Object self,
Closure<T> closure)
Allows the closure to be called for the object reference self.
|
static <T> T |
withDataInputStream(File file,
Closure<T> closure)
Create a new DataInputStream for this file and passes it into the closure.
|
static <T> T |
withDataOutputStream(File file,
Closure<T> closure)
Create a new DataOutputStream for this file and passes it into the closure.
|
static <K,V> Map<K,V> |
withDefault(Map<K,V> self,
Closure init)
Wraps a map using the delegate pattern with a wrapper that intercepts all calls
to
get(key) . |
static Object |
withInputStream(File file,
Closure closure)
Create a new InputStream for this file and passes it into the closure.
|
static <T> T |
withInputStream(URL url,
Closure<T> closure)
Creates a new InputStream for this URL and passes it into the closure.
|
static <T> T |
withObjectInputStream(File file,
ClassLoader classLoader,
Closure<T> closure)
Create a new ObjectInputStream for this file associated with the given class loader and pass it to the closure.
|
static <T> T |
withObjectInputStream(File file,
Closure<T> closure)
Create a new ObjectInputStream for this file and pass it to the closure.
|
static <T> T |
withObjectInputStream(InputStream inputStream,
ClassLoader classLoader,
Closure<T> closure)
Create a new ObjectInputStream for this file and pass it to the closure.
|
static <T> T |
withObjectInputStream(InputStream inputStream,
Closure<T> closure)
Create a new ObjectInputStream for this file and pass it to the closure.
|
static <T> T |
withObjectOutputStream(File file,
Closure<T> closure)
Create a new ObjectOutputStream for this file and then pass it to the
closure.
|
static <T> T |
withObjectOutputStream(OutputStream outputStream,
Closure<T> closure)
Create a new ObjectOutputStream for this output stream and then pass it to the
closure.
|
static <T> T |
withObjectStreams(Socket socket,
Closure<T> closure)
Creates an InputObjectStream and an OutputObjectStream from a Socket, and
passes them to the closure.
|
static Object |
withOutputStream(File file,
Closure closure)
Creates a new OutputStream for this file and passes it into the closure.
|
static <T> T |
withPrintWriter(File file,
Closure<T> closure)
Create a new PrintWriter for this file which is then
passed it into the given closure.
|
static <T> T |
withPrintWriter(File file,
String charset,
Closure<T> closure)
Create a new PrintWriter with a specified charset for
this file.
|
static <T> T |
withPrintWriter(Writer writer,
Closure<T> closure)
Create a new PrintWriter with a specified charset for
this file.
|
static <T> T |
withReader(File file,
Closure<T> closure)
Create a new BufferedReader for this file and then
passes it into the closure, ensuring the reader is closed after the
closure returns.
|
static <T> T |
withReader(File file,
String charset,
Closure<T> closure)
Create a new BufferedReader for this file using the specified charset and then
passes it into the closure, ensuring the reader is closed after the
closure returns.
|
static <T> T |
withReader(InputStream in,
Closure<T> closure)
Helper method to create a new Reader for a stream and then
passes it into the closure.
|
static <T> T |
withReader(InputStream in,
String charset,
Closure<T> closure)
Helper method to create a new Reader for a stream and then
passes it into the closure.
|
static <T> T |
withReader(Reader reader,
Closure<T> closure)
Allows this reader to be used within the closure, ensuring that it
is closed before this method returns.
|
static <T> T |
withReader(URL url,
Closure<T> closure)
Helper method to create a new BufferedReader for a URL and then
passes it to the closure.
|
static <T> T |
withReader(URL url,
String charset,
Closure<T> closure)
Helper method to create a new Reader for a URL and then
passes it to the closure.
|
static <T> T |
withStream(InputStream stream,
Closure<T> closure)
Allows this input stream to be used within the closure, ensuring that it
is flushed and closed before this method returns.
|
static <T> T |
withStream(OutputStream os,
Closure<T> closure)
Passes this OutputStream to the closure, ensuring that the stream
is closed after the closure returns, regardless of errors.
|
static <T> T |
withStreams(Socket socket,
Closure<T> closure)
Passes the Socket's InputStream and OutputStream to the closure.
|
static <T> T |
withWriter(File file,
Closure<T> closure)
Creates a new BufferedWriter for this file, passes it to the closure, and
ensures the stream is flushed and closed after the closure returns.
|
static <T> T |
withWriter(File file,
String charset,
Closure<T> closure)
Creates a new BufferedWriter for this file, passes it to the closure, and
ensures the stream is flushed and closed after the closure returns.
|
static <T> T |
withWriter(OutputStream stream,
Closure<T> closure)
Creates a writer from this stream, passing it to the given closure.
|
static <T> T |
withWriter(OutputStream stream,
String charset,
Closure<T> closure)
Creates a writer from this stream, passing it to the given closure.
|
static <T> T |
withWriter(Writer writer,
Closure<T> closure)
Allows this writer to be used within the closure, ensuring that it
is flushed and closed before this method returns.
|
static <T> T |
withWriterAppend(File file,
Closure<T> closure)
Create a new BufferedWriter for this file in append mode.
|
static <T> T |
withWriterAppend(File file,
String charset,
Closure<T> closure)
Create a new BufferedWriter which will append to this
file.
|
static void |
write(File file,
String text)
Write the text to the File.
|
static void |
write(File file,
String text,
String charset)
Write the text to the File, using the specified encoding.
|
static void |
write(Writer self,
Writable writable)
A helper method so that dynamic dispatch of the writer.write(object) method
will always use the more efficient Writable.writeTo(writer) mechanism if the
object implements the Writable interface.
|
static void |
writeLine(BufferedWriter writer,
String line)
Write the text and append a newline (using the platform's line-ending).
|
static BitSet |
xor(BitSet left,
BitSet right)
Bitwise XOR together two BitSets.
|
static Boolean |
xor(Boolean left,
Boolean right)
Exclusive disjunction of two boolean operators
|
static Number |
xor(Number left,
Number right)
Bitwise XOR together two Numbers.
|
cloneSimilarCollection, cloneSimilarMap, closeQuietly, closeWithWarning, createSimilarCollection, createSimilarCollection, createSimilarList, createSimilarMap, createSimilarOrDefaultCollection, createSimilarSet, normaliseIndex, sameType, subListBorders, subListBorders
public static final Class[] additionals
public static boolean is(Object self, Object other)
def same = this.is(that)
self
- an objectother
- an object to compare identity withpublic static <T> T identity(Object self, Closure<T> closure)
self
- the object to have a closure act uponclosure
- the closure to call on the objectpublic static <T> T with(Object self, Closure<T> closure)
def b = new StringBuilder().with { append('foo') append('bar') return it } assert b.toString() == 'foobar'This is commonly used to simplify object creation, such as this example:
def p = new Person().with { firstName = 'John' lastName = 'Doe' return it }
self
- the object to have a closure act uponclosure
- the closure to call on the objectpublic static Object getAt(Object self, String property)
bean[somePropertyNameExpression]
. The normal property notation
of groovy is neater and more concise but only works with compile-time known
property names.self
- the object to act uponproperty
- the property name of interestpublic static void putAt(Object self, String property, Object newValue)
bean[somePropertyNameExpression] = foo
. The normal property notation
of groovy is neater and more concise but only works with property names which
are known at compile time.self
- the object to act uponproperty
- the name of the property to setnewValue
- the value to setpublic static String dump(Object self)
self
- an objectpublic static List<PropertyValue> getMetaPropertyValues(Object self)
MetaProperty
objects for 'self' and wraps it
in a list of PropertyValue
objects that additionally provide
the value for each property of 'self'.self
- the receiver objectPropertyValue
objectsExpando.getMetaPropertyValues()
public static Map getProperties(Object self)
getMetaPropertyValues(java.lang.Object)
(self)
and provides the data in form of simple key/value pairs, i.e.&nsbp;without
type() information.self
- the receiver objectpublic static <T> T use(Object self, Class categoryClass, Closure<T> closure)
self
- any ObjectcategoryClass
- a category class to useclosure
- the closure to invoke with the category in placepublic static void mixin(MetaClass self, List<Class> categoryClasses)
self
- any ClasscategoryClasses
- a category classes to usepublic static void mixin(Class self, List<Class> categoryClasses)
self
- any ClasscategoryClasses
- a category classes to usepublic static void mixin(Class self, Class categoryClass)
self
- any ClasscategoryClass
- a category class to usepublic static void mixin(Class self, Class[] categoryClass)
self
- any ClasscategoryClass
- a category class to usepublic static void mixin(MetaClass self, Class categoryClass)
self
- any ClasscategoryClass
- a category class to usepublic static void mixin(MetaClass self, Class[] categoryClass)
self
- any ClasscategoryClass
- a category class to usepublic static <T> T use(Object self, List<Class> categoryClassList, Closure<T> closure)
self
- any ObjectcategoryClassList
- a list of category classesclosure
- the closure to invoke with the categories in placepublic static void addShutdownHook(Object self, Closure closure)
self
- the object the method is called on (ignored)closure
- the shutdown hook actionpublic static Object use(Object self, Object[] array)
use(CategoryClass1, CategoryClass2) { ... }
This method saves having to wrap the the category
classes in a list.self
- any Objectarray
- a list of category classes and a Closurepublic static void print(Object self, Object value)
self
- any Objectvalue
- the value to printpublic static void print(PrintWriter self, Object value)
self
- a PrintWritervalue
- the value to printpublic static void print(PrintStream self, Object value)
self
- a PrintStreamvalue
- the value to printpublic static void print(Closure self, Object value)
self
- a generated closurevalue
- the value to printpublic static void println(Object self)
self
- any Objectpublic static void println(Closure self)
self
- a closurepublic static void println(Object self, Object value)
self
- any Objectvalue
- the value to printpublic static void println(PrintWriter self, Object value)
self
- a PrintWritervalue
- the value to printpublic static void println(PrintStream self, Object value)
self
- any Objectvalue
- the value to printpublic static void println(Closure self, Object value)
self
- a closurevalue
- the value to printpublic static void printf(Object self, String format, Object[] values)
self
- any Objectformat
- a format stringvalues
- values referenced by the format specifiers in the format string.public static String sprintf(Object self, String format, Object[] values)
self
- any Objectformat
- a format stringvalues
- values referenced by the format specifiers in the format string.public static void printf(Object self, String format, Object arg)
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 ]) ( 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[] ) }
self
- any Objectformat
- A format stringarg
- Argument which is referenced by the format specifiers in the format
string. The type of arg
should be one of Object[], List,
int[], short[], byte[], char[], boolean[], long[], float[], or double[].public static String sprintf(Object self, String format, Object arg)
self
- any Objectformat
- A format stringarg
- Argument which is referenced by the format specifiers in the format
string. The type of arg
should be one of Object[], List,
int[], short[], byte[], char[], boolean[], long[], float[], or double[].public static String inspect(Object self)
self
- any Objectpublic static void print(Object self, PrintWriter out)
self
- any Objectout
- the PrintWriter used for printingpublic static void println(Object self, PrintWriter out)
self
- any Objectout
- the PrintWriter used for printingpublic static Object invokeMethod(Object object, String method, Object arguments)
object
- any Objectmethod
- the name of the method to callarguments
- the arguments to usepublic static boolean isCase(Object caseValue, Object switchValue)
switch( a ) { case b: //some code }"some code" is called when
b.isCase( a )
returns
true
.caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(String caseValue, Object switchValue)
switch( str ) { case 'one' : // etc... }Note that this returns
true
for the case where both the
'switch' and 'case' operand is null
.caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(CharSequence caseValue, Object switchValue)
caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(GString caseValue, Object switchValue)
caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(Class caseValue, Object switchValue)
switch( obj ) { case List : // obj is a list break; case Set : // etc }
caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(Collection caseValue, Object switchValue)
switch( 3 ) { case [1,3,5]: assert true break default: assert false }
caseValue
- the case valueswitchValue
- the switch valueCollection.contains(java.lang.Object)
public static boolean isCase(Map caseValue, Object switchValue)
switch( 'foo' ) { case [foo:true, bar:false]: assert true break default: assert false }
caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(Pattern caseValue, Object switchValue)
Pattern
class, which allows
testing a String against a number of regular expressions.
For example:
switch( str ) { case ~/one/ : // the regex 'one' matches the value of str }Note that this returns true for the case where both the pattern and the 'switch' values are
null
.caseValue
- the case valueswitchValue
- the switch valuepublic static boolean isCase(Number caseValue, Number switchValue)
compareTo()
method for comparing numbers of different
types.caseValue
- the case valueswitchValue
- the switch valuepublic static <T> Iterator<T> unique(Iterator<T> self)
self
- an Iteratorpublic static <T> Collection<T> unique(Collection<T> self)
assert [1,3] == [1,3,3].unique()
self
- a collectionunique(Collection, boolean)
public static <T> Collection<T> unique(Collection<T> self, boolean mutate)
assert [1,3] == [1,3,3].unique()
def orig = [1, 3, 2, 3] def uniq = orig.unique(false) assert orig == [1, 3, 2, 3] assert uniq == [1, 3, 2]
self
- a collectionmutate
- false will cause a new list containing unique items from the collection to be created, true will mutate collections in placepublic static int numberAwareCompareTo(Comparable self, Comparable other)
self
- a Comparableother
- another Comparablepublic static <T> Iterator<T> unique(Iterator<T> self, Closure closure)
Comparable.compareTo(java.lang.Object)
or 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).self
- an Iteratorclosure
- a Closure used to determine unique itemspublic static <T> Collection<T> unique(Collection<T> self, Closure closure)
Comparable.compareTo(java.lang.Object)
or 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).
assert [1,4] == [1,3,4,5].unique { it % 2 }
assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }
self
- a Collectionclosure
- a 1 or 2 arg Closure used to determine unique itemsunique(Collection, boolean, Closure)
public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Closure closure)
Comparable.compareTo(java.lang.Object)
or 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).
def orig = [1, 3, 4, 5] def uniq = orig.unique(false) { it % 2 } assert orig == [1, 3, 4, 5] assert uniq == [1, 4]
def orig = [2, 3, 3, 4] def uniq = orig.unique(false) { a, b -> a <=> b } assert orig == [2, 3, 3, 4] assert uniq == [2, 3, 4]
self
- a Collectionmutate
- false will always cause a new list to be created, true will mutate lists in placeclosure
- a 1 or 2 arg Closure used to determine unique itemspublic static <T> Iterator<T> unique(Iterator<T> self, Comparator<T> comparator)
self
- an Iteratorcomparator
- a Comparatorpublic static <T> Collection<T> unique(Collection<T> self, Comparator<T> comparator)
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 && list == [a, b, c] )
self
- a Collectioncomparator
- a Comparatorunique(java.util.Collection, boolean, java.util.Comparator)
public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<T> comparator)
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 && list2 == [a, b, c] )
self
- a Collectionmutate
- false will always cause a new collection to be created, true will mutate collections in placecomparator
- a Comparatorpublic static <T> T each(T self, Closure closure)
self
- the object over which we iterateclosure
- the closure applied on each element foundpublic static <T> T eachWithIndex(T self, Closure closure)
self
- an Objectclosure
- a Closure to operate on each itempublic static <K,V> Map<K,V> each(Map<K,V> self, Closure closure)
def result = "" [a:1, b:3].each { key, value -> result += "$key$value" } assert result == "a1b3"
def result = "" [a:1, b:3].each { entry -> result += entry } assert result == "a=1b=3"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.
self
- the map over which we iterateclosure
- the 1 or 2 arg closure applied on each entry of the mappublic static <K,V> Map<K,V> reverseEach(Map<K,V> self, Closure closure)
self
- the map over which we iterateclosure
- the 1 or 2 arg closure applied on each entry of the mapeach(Map, Closure)
public static <K,V> Map<K,V> eachWithIndex(Map<K,V> self, Closure closure)
def result = "" [a:1, b:3].eachWithIndex { key, value, index -> result += "$index($key$value)" } assert result == "0(a1)1(b3)"
def result = "" [a:1, b:3].eachWithIndex { entry, index -> result += "$index($entry)" } assert result == "0(a=1)1(b=3)"
self
- the map over which we iterateclosure
- a 2 or 3 arg Closure to operate on each itempublic static <T> List<T> reverseEach(List<T> self, Closure closure)
def result = [] [1,2,3].reverseEach { result << it } assert result == [3,2,1]
self
- a Listclosure
- a closure to which each item is passed.public static <T> T[] reverseEach(T[] self, Closure closure)
self
- an Object arrayclosure
- a closure to which each item is passedpublic static boolean every(Object self, Closure closure)
true
for all items in this data structure).
A simple example for a list:
def list = [3,4,5] def greaterThanTwo = list.every { it > 2 }
self
- the object over which we iterateclosure
- the closure predicate used for matchingpublic static <K,V> boolean every(Map<K,V> self, Closure closure)
def map = [a:1, b:2.0, c:2L] assert !map.every { key, value -> value instanceof Integer } assert map.every { entry -> entry.value instanceof Number }
self
- the map over which we iterateclosure
- the 1 or 2 arg Closure predicate used for matchingpublic static boolean every(Object self)
true
according to the Groovy Truth.
Equivalent to self.every({element -> element})
self
- the object over which we iteratepublic static boolean any(Object self, Closure closure)
self
- the object over which we iterateclosure
- the closure predicate used for matchingpublic static <K,V> boolean any(Map<K,V> self, Closure<?> closure)
assert [2:3, 4:5, 5:10].any { key, value -> key * 2 == value } assert ![2:3, 4:5, 5:10].any { entry -> entry.key == entry.value * 2 }
self
- the map over which we iterateclosure
- the 1 or 2 arg closure predicate used for matchingpublic static boolean any(Object self)
self
- the object over which we iteratepublic static Collection grep(Object self, Object filter)
isCase(java.lang.Object, java.lang.Object)
method used by switch statements. This method can be used with different
kinds of filters like regular expressions, classes, ranges etc.
Example:
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 ]
self
- the object over which we iteratefilter
- the filter to perform on the object (using the isCase(java.lang.Object, java.lang.Object)
method)public static Collection grep(Object self)
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.grep() == [1, 2, true, 'foo', [4, 5]]
self
- the object over which we iterateClosure.IDENTITY
public static Number count(Iterator self, Object value)
compareTo(value) == 0
or equals(value)
).
The iterator will become exhausted of elements after determining the count value.self
- the Iterator from which we count the number of matching occurrencesvalue
- the value being searched forpublic static Number count(Iterator self, Closure closure)
Example usage:
assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2
self
- the Iterator from which we count the number of matching occurrencesclosure
- a closure conditionpublic static Number count(Collection self, Object value)
compareTo(value) == 0
or equals(value)
).
Example usage:
assert [2,4,2,1,3,5,2,4,3].count(4) == 2
self
- the collection within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(Collection self, Closure closure)
Example usage:
assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5
self
- the collection within which we count the number of occurrencesclosure
- a closure conditionpublic static Number count(Map self, Closure<?> closure)
Example usage:
assert [a:1, b:1, c:2, d:2].count{ k,v -> k == 'a' || v == 2 } == 3
self
- the map within which we count the number of occurrencesclosure
- a 1 or 2 arg Closure condition applying on the entriespublic static Number count(Object[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(Object[] self, Closure closure)
self
- the array within which we count the number of occurrencesclosure
- a closure conditionpublic static Number count(int[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(long[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(short[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(char[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(boolean[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(double[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(float[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static Number count(byte[] self, Object value)
compareTo(value) == 0
or equals(value)
).self
- the array within which we count the number of occurrencesvalue
- the value being searched forpublic static <T> List<T> toList(Collection<T> self)
Example usage:
def x = [1,2,3] as HashSet assert x.class == HashSet assert x.toList() instanceof List
self
- a collectionpublic static <T> List<T> toList(Iterator<T> self)
self
- an iteratorpublic static <T> List<T> toList(Enumeration<T> self)
self
- an enumerationpublic static <T> List<T> collect(Object self, Closure<T> closure)
def list = [1, 'a', 1.23, true ] def types = list.collect { it.class } assert types == [Integer, String, BigDecimal, Boolean]
self
- the values of the object to transformclosure
- the closure used to transform each element of the collectionpublic static <T> Collection<T> collect(Object self, Collection<T> collection, Closure<? extends T> closure)
self
- the values of the object to transformcollection
- the Collection to which the transformed values are addedclosure
- the closure used to map each element of the collectionpublic static <T> List<T> collect(Collection<?> self, Closure<T> closure)
assert [2,4,6] == [1,2,3].collect { it * 2 }
self
- a collectionclosure
- the closure used for mappingpublic static <T> Collection<T> collect(Collection<?> self, Collection<T> collection, Closure<? extends T> closure)
assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }
self
- a collectioncollection
- an initial Collection to which the transformed values are addedclosure
- the closure used to transform each element of the collectionpublic static List collectAll(Collection self, Closure closure)
collectNested(Collection, Closure)
public static List collectNested(Collection self, Closure closure)
assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
self
- a collectionclosure
- the closure used to transform each element of the collectionpublic static Collection collectAll(Collection self, Collection collection, Closure closure)
collectNested(Collection, Collection, Closure)
public static Collection collectNested(Collection self, Collection collection, Closure closure)
def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 } assert x == [2,[4,6],[8],[]] assert x instanceof Vector
self
- a collectioncollection
- an initial Collection to which the transformed values are addedclosure
- the closure used to transform each element of the collectionpublic static <T> Collection<T> collectMany(Collection self, Closure<Collection<T>> closure)
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() > 3 ? [] : [it.toLowerCase()] } assert smallAnimals == ['cat', 'dog'] as Set
self
- a collectionclosure
- a projecting Closure returning a collection of itemssum(java.util.Collection, groovy.lang.Closure)
public static <T> Collection<T> collectMany(Object[] self, Closure<Collection<T>> closure)
def nums = [1, 2, 3, 4, 5, 6] as Object[] def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] } assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
self
- an object arrayclosure
- a projecting Closure returning a collection of itemssum(Object[], groovy.lang.Closure)
public static <T> Collection<T> collectMany(Iterator<Object> self, Closure<Collection<T>> closure)
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]
self
- an iteratorclosure
- a projecting Closure returning a collection of itemssum(Iterator, groovy.lang.Closure)
public static <T> Collection<T> collect(Map<?,?> self, Collection<T> collection, Closure<? extends T> closure)
assert [a:1, b:2].collect( [] as HashSet ) { key, value -> key*value } == ["a", "bb"] as Set assert [3:20, 2:30].collect( [] as HashSet ) { entry -> entry.key * entry.value } == [60] as Set
self
- a Mapcollection
- the Collection to which the mapped values are addedclosure
- the closure used for mapping, which can take one (Map.Entry) or two (key, value) parameterspublic static <T> List<T> collect(Map self, Closure<T> closure)
assert [a:1, b:2].collect { key, value -> key*value } == ["a", "bb"] assert [3:20, 2:30].collect { entry -> entry.key * entry.value } == [60, 60]
self
- a Mapclosure
- the closure used to map each element of the collectionpublic static <K,V> Map<K,V> collectEntries(Map<?,?> self, Map<K,V> result, Closure<?> closure)
assert [a:1, b:2].collectEntries( [:] ) { k, v -> [v, k] } == [1:'a', 2:'b'] assert [a:1, b:2].collectEntries( [30:'C'] ) { key, value -> [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
self
- a Mapresult
- the Map into which the mapped entries are putclosure
- the closure used for mapping, 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 valuecollect(Map, Collection, Closure)
public static Map<?,?> collectEntries(Map<?,?> self, Closure<?> closure)
assert [a:1, b:2].collectEntries { key, value -> [value, key] } == [1:'a', 2:'b'] assert [a:1, b:2].collectEntries { key, value -> [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
self
- a Mapclosure
- the closure used for mapping, 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 valuecollect(Map, Collection, Closure)
public static <K,V> Map<K,V> collectEntries(Collection<?> self, Map<K,V> result, Closure<?> closure)
def letters = "abc" // collect letters with index assert (0..2).collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] assert (0..2).collectEntries( [4:'d'] ) { index -> [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
self
- a Collectionresult
- the Map into which the collected entries are putclosure
- the closure used for mapping, 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 valuecollect(Map, Collection, Closure)
public static <K,V> Map<K,V> collectEntries(Object[] self, Map<K,V> result, Closure<?> closure)
def letters = "abc" def nums = [0, 1, 2] as Integer[] // collect letters with index assert nums.collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] assert nums.collectEntries( [4:'d'] ) { index -> [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
self
- a Collectionresult
- the Map into which the collected entries are putclosure
- the closure used for mapping, 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 valuecollect(Map, Collection, Closure)
public static <K,V> Map<K,V> collectEntries(Collection<?> self, Closure<?> closure)
def letters = "abc" // collect letters with index using list style assert (0..2).collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] // collect letters with index using map style assert (0..2).collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
self
- a Collectionclosure
- the closure used for mapping, 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 valuecollectEntries(Collection, Map, Closure)
public static <K,V> Map<K,V> collectEntries(Object[] self, Closure<?> closure)
def letters = "abc" def nums = [0, 1, 2] as Integer[] // collect letters with index using list style assert nums.collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] // collect letters with index using map style assert nums.collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
self
- a Collectionclosure
- the closure used for mapping, 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 valuecollectEntries(Collection, Map, Closure)
public static Object find(Object self, Closure closure)
self
- an Object with an iterator returning its valuesclosure
- a closure conditionpublic static Object find(Object self)
def items = [null, 0, 0.0, false, '', [], 42, 43] assert items.find() == 42
self
- an Object with an Iterator returning its valuesClosure.IDENTITY
public static Object findResult(Object self, Object defaultResult, Closure closure)
self
- an Object with an iterator returning its valuesdefaultResult
- an Object that should be returned if all closure results are nullclosure
- a closure that returns a non-null value when processing should stoppublic static Object findResult(Object self, Closure closure)
self
- an Object with an iterator returning its valuesclosure
- a closure that returns a non-null value when processing should stoppublic static <T> T find(Collection<T> self, Closure closure)
def list = [1,2,3] assert 2 == list.find { it > 1 }
self
- a Collectionclosure
- a closure conditionpublic static <T> T find(Collection<T> self)
def items = [null, 0, 0.0, false, '', [], 42, 43] assert items.find() == 42
self
- a CollectionClosure.IDENTITY
public static <T,U extends T,V extends T> T findResult(Collection<?> self, U defaultResult, Closure<V> closure)
def list = [1,2,3] assert "Found 2" == list.findResult("default") { it > 1 ? "Found $it" : null } assert "default" == list.findResult("default") { it > 3 ? "Found $it" : null }
self
- a CollectiondefaultResult
- an Object that should be returned if all closure results are nullclosure
- a closure that returns a non-null value when processing should stop and a value should be returnedpublic static <T> T findResult(Collection<?> self, Closure<T> closure)
def list = [1,2,3] assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }
self
- a Collectionclosure
- a closure that returns a non-null value when processing should stop and a value should be returnedpublic static <T> Collection<T> findResults(Collection<?> self, Closure<T> filteringTransform)
def list = [1,2,3] def result = list.findResults { it > 1 ? "Found $it" : null } assert result == ["Found 2", "Found 3"]
self
- a CollectionfilteringTransform
- a Closure that should return either a non-null transformed value or null for items which should be discardedpublic static <T> Collection<T> findResults(Map<?,?> self, Closure<T> filteringTransform)
def map = [a:1, b:2, hi:2, cat:3, dog:2] def result = map.findResults { k, v -> k.size() == v ? "Found $k:$v" : null } assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
self
- a MapfilteringTransform
- a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discardedpublic static <K,V> Map.Entry<K,V> find(Map<K,V> self, Closure<?> closure)
assert [a:1, b:3].find { it.value == 3 }.key == "b"
self
- a Mapclosure
- a 1 or 2 arg Closure conditionpublic static <T,U extends T,V extends T> T findResult(Map<?,?> self, U defaultResult, Closure<V> closure)
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 -> if (k.size() + v == 2) return "Found $k:$v" }
self
- a MapdefaultResult
- an Object that should be returned if all closure results are nullclosure
- a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returnedpublic static <T> T findResult(Map<?,?> self, Closure<T> closure)
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 -> if (k.size() + v == 2) return "Found $k:$v" }
self
- a Mapclosure
- a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returnedpublic static <T> Collection<T> findAll(Collection<T> self, Closure closure)
assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }
self
- a Collectionclosure
- a closure conditionpublic static <T> Collection<T> findAll(Collection<T> self)
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
self
- a CollectionClosure.IDENTITY
public static Collection findAll(Object self, Closure closure)
self
- an Object with an Iterator returning its valuesclosure
- a closure conditionpublic static Collection findAll(Object self)
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
self
- an Object with an Iterator returning its valuesClosure.IDENTITY
public static boolean containsAll(Collection self, Object[] items)
self
- a Collection to be checked for containmentitems
- array to be checked for containment in this collectionCollection.containsAll(Collection)
public static boolean removeAll(Collection self, Object[] items)
findAll
and grep
when wanting to produce a new list
containing items which don't match some criteria while leaving the original collection unchanged.self
- a Collection to be modifieditems
- array containing elements to be removed from this collectionCollection.removeAll(Collection)
public static boolean retainAll(Collection self, Object[] items)
grep
and findAll
when wanting to produce a new list
containing items which match some specified items but leaving the original collection unchanged.self
- a Collection to be modifieditems
- array containing elements to be retained from this collectionCollection.retainAll(Collection)
public static boolean retainAll(Collection self, Closure condition)
findAll
and grep
when wanting to produce a new list
containing items which match some criteria but leaving the original collection unchanged.self
- a Collection to be modifiedcondition
- a closure conditionIterator.remove()
public static boolean removeAll(Collection self, Closure condition)
findAll
and grep
when wanting to produce a new list
containing items which don't match some criteria while leaving the original collection unchanged.self
- a Collection to be modifiedcondition
- a closure conditionIterator.remove()
public static <T> boolean addAll(Collection<T> self, T[] items)
plus
or the '+' operator if wanting to produce a new collection
containing additional items but while leaving the original collection unchanged.self
- a Collection to be modifieditems
- array containing elements to be added to this collectionCollection.addAll(Collection)
public static <T> boolean addAll(List<T> self, int index, T[] items)
plus
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.self
- a list to be modifieditems
- array containing elements to be added to this collectionindex
- index at which to insert the first element from the
specified arrayList.addAll(int, Collection)
public static Collection split(Object self, Closure closure)
self
- an Object with an Iterator returning its valuesclosure
- a closure conditionpublic static <T> Collection<Collection<T>> split(Collection<T> self, Closure closure)
Example usage:
assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }
self
- a Collection of valuesclosure
- a closure conditionpublic static List combinations(Collection self)
Example usage:
assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
self
- a Collection of listsGroovyCollections.combinations(java.util.Collection)
public static <T> Set<List<T>> subsequences(List<T> self)
Example usage:
def result = [1, 2, 3].subsequences() assert result == [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] as Set
self
- the List of itemspublic static <T> Set<List<T>> permutations(List<T> self)
Example usage:
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
self
- the Collection of itemspublic static <T> Iterator<List<T>> eachPermutation(Collection<T> self, Closure closure)
Example usage:
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]]
self
- the Collection of itemsclosure
- the closure to call for each permutationpublic static List transpose(List self)
Example usage:
def result = [['a', 'b'], [1, 2]].transpose() assert result == [['a', 1], ['b', 2]]
def result = [['a', 'b'], [1, 2], [3, 4]].transpose() assert result == [['a', 1, 3], ['b', 2, 4]]
self
- a List of listsGroovyCollections.transpose(java.util.List)
public static <K,V> Map<K,V> findAll(Map<K,V> self, Closure closure)
If the self
map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
Example usage:
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]
self
- a Mapclosure
- a 1 or 2 arg Closure condition applying on the entriespublic static <K,T> Map<K,List<T>> groupBy(Collection<T> self, Closure<K> closure)
Example usage:
assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }
self
- a collection to groupclosure
- a closure mapping entries on keyspublic static Map groupBy(Collection self, Object... closures)
Example usage:
def result = [1,2,3,4,5,6].groupBy({ it % 2 }, { it < 4 }) assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]Another example:
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 }If an empty array of closures is supplied the IDENTITY Closure will be used.
self
- a collection to groupclosures
- an array of closures, each mapping entries on keysClosure.IDENTITY
public static Map groupBy(Collection self, List<Closure> closures)
Example usage:
def result = [1,2,3,4,5,6].groupBy([{ it % 2 }, { it < 4 }]) assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]Another example:
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 }If an empty list of closures is supplied the IDENTITY Closure will be used.
self
- a collection to groupclosures
- a list of closures, each mapping entries on keysClosure.IDENTITY
public static <K> Map<K,Integer> countBy(Collection self, Closure<K> closure)
Example usage:
assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }
self
- a collection to group and countclosure
- a closure mapping items to the frequency keyspublic static <K> Map<K,Integer> countBy(Object[] self, Closure<K> closure)
Example usage:
assert ([1,2,2,2,3] as Object[]).countBy{ it % 2 } == [1:2, 0:3]
self
- an object array to group and countclosure
- a closure mapping items to the frequency keyscountBy(Collection, Closure)
public static <K> Map<K,Integer> countBy(Iterator self, Closure<K> closure)
Example usage:
assert [1,2,2,2,3].toSet().iterator().countBy{ it % 2 } == [1:2, 0:1]
self
- an iterator to group and countclosure
- a closure mapping items to the frequency keyscountBy(Collection, Closure)
public static <G,K,V> Map<G,List<Map.Entry<K,V>>> groupEntriesBy(Map<K,V> self, Closure<G> closure)
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]
self
- a map to groupclosure
- a 1 or 2 arg Closure mapping entries on keyspublic static <G,K,V> Map<G,Map<K,V>> groupBy(Map<K,V> self, Closure<G> closure)
If the self
map is one of TreeMap, Hashtable or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
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]]
self
- a map to groupclosure
- a closure mapping entries on keyspublic static Map<Object,Map> groupBy(Map self, Object... closures)
If the self
map is one of TreeMap, Hashtable, or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
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]]]If an empty array of closures is supplied the IDENTITY Closure will be used.
self
- a map to groupclosures
- an array of closures that map entries on keysClosure.IDENTITY
public static Map<Object,Map> groupBy(Map self, List<Closure> closures)
If the self
map is one of TreeMap, Hashtable, or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
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]]]If an empty list of closures is supplied the IDENTITY Closure will be used.
self
- a map to groupclosures
- a list of closures that map entries on keysClosure.IDENTITY
public static <K> Map<K,Integer> countBy(Map self, Closure<K> closure)
def result = [a:1,b:2,c:3,d:4,e:5].countBy { it.value % 2 } assert result == [0:2, 1:3]
self
- a map to group and countclosure
- a closure mapping entries to frequency count keysprotected static <K,T> void groupAnswer(Map<K,List<T>> answer, T element, K value)
answer
- the map containing the resultselement
- the element to be placedvalue
- the value according to which the element will be placedprotected static <T> T callClosureForMapEntry(Closure<T> closure, Map.Entry entry)
protected static <T> T callClosureForLine(Closure<T> closure, String line, int counter)
protected static <T> T callClosureForMapEntryAndCounter(Closure<T> closure, Map.Entry entry, int counter)
public static <T,U extends T,V extends T> T inject(Collection self, U initialValue, Closure<V> closure)
assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val } assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val } assert 'The quick brown fox' == ['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val } assert 'bat' == ['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min } def max = { a, b -> [a, b].max() } def animals = ['bat', 'rat', 'cat'] assert 'rat' == animals.inject('aaa', max)Visual representation of the last example above:
initVal animals[0] v v max('aaa', 'bat') => 'bat' animals[1] v v max('bat', 'rat') => 'rat' animals[2] v v max('rat', 'cat') => 'rat'
self
- a CollectioninitialValue
- some initial valueclosure
- a closurepublic static <T,U extends T,V extends T> T inject(Map<?,?> self, U initialValue, Closure<V> closure)
def map = [a:1, b:2, c:3] assert map.inject([]) { list, k, v -> list + [k] * v } == ['a', 'b', 'b', 'c', 'c', 'c']
self
- a MapinitialValue
- some initial valueclosure
- a 2 or 3 arg Closurepublic static <T,U extends T,V extends T> T inject(Iterator self, U initialValue, Closure<V> closure)
self
- an IteratorinitialValue
- some initial valueclosure
- a closureinject(Collection, Object, Closure)
public static <T,U extends T,V extends T> T inject(Object self, U initialValue, Closure<V> closure)
self
- an ObjectinitialValue
- some initial valueclosure
- a closureinject(Collection, Object, Closure)
public static <T,U extends T,V extends T> T inject(Object[] self, U initialValue, Closure<V> closure)
self
- an Object[]initialValue
- some initial valueclosure
- a closureinject(Collection, Object, Closure)
public static Object sum(Collection self)
assert 1+2+3+4 == [1,2,3,4].sum()
self
- Collection of values to add togetherpublic static Object sum(Object[] self)
self
- The array of values to add togethersum(java.util.Collection)
public static Object sum(Iterator<Object> self)
self
- an Iterator for the values to add togetherpublic static Object sum(Collection self, Object initialValue)
assert 5+1+2+3+4 == [1,2,3,4].sum(5)
self
- a collection of values to suminitialValue
- the items in the collection will be summed to this initial valuepublic static Object sum(Object[] self, Object initialValue)
self
- an array of values to suminitialValue
- the items in the array will be summed to this initial valuepublic static Object sum(Iterator<Object> self, Object initialValue)
self
- an Iterator for the values to add togetherinitialValue
- the items in the collection will be summed to this initial valuepublic static Object sum(Collection self, Closure closure)
coll.sum(closure)
is equivalent to:
coll.collect(closure).sum()
.
assert 4+6+10+12 == [2,3,5,6].sum() { it * 2 }
self
- a Collectionclosure
- a single parameter closure that returns a numeric value.public static Object sum(Object[] self, Closure closure)
array.sum(closure)
is equivalent to:
array.collect(closure).sum()
.self
- An arrayclosure
- a single parameter closure that returns a numeric value.public static Object sum(Iterator<Object> self, Closure closure)
iter.sum(closure)
is equivalent to:
iter.collect(closure).sum()
. The iterator will become
exhausted of elements after determining the sum value.self
- An Iteratorclosure
- a single parameter closure that returns a numeric value.public static Object sum(Collection self, Object initialValue, Closure closure)
coll.sum(initVal, closure)
is equivalent to:
coll.collect(closure).sum(initVal)
.
assert 50+4+6+10+12 == [2,3,5,6].sum(50) { it * 2 }
self
- a Collectionclosure
- a single parameter closure that returns a numeric value.initialValue
- the closure results will be summed to this initial valuepublic static Object sum(Object[] self, Object initialValue, Closure closure)
array.sum(initVal, closure)
is equivalent to:
array.collect(closure).sum(initVal)
.self
- an arrayclosure
- a single parameter closure that returns a numeric value.initialValue
- the closure results will be summed to this initial valuepublic static Object sum(Iterator<Object> self, Object initialValue, Closure closure)
iter.sum(initVal, closure)
is equivalent to:
iter.collect(closure).sum(initVal)
. The iterator will become
exhausted of elements after determining the sum value.self
- an Iteratorclosure
- a single parameter closure that returns a numeric value.initialValue
- the closure results will be summed to this initial valuepublic static String join(Iterator<Object> self, String separator)
toString()
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.self
- an Iterator of itemsseparator
- a String separatorpublic static String join(Collection self, String separator)
toString()
representation of each
item in this collection, with the given String as a separator between
each item.
assert "1, 2, 3" == [1,2,3].join(", ")
self
- a Collection of objectsseparator
- a String separatorpublic static String join(Object[] self, String separator)
toString()
representation of each
items in this array, with the given String as a separator between each
item.self
- an array of Objectseparator
- a String separatorpublic static <T> T min(Collection<T> self)
assert 2 == [4,2,5].min()
self
- a CollectionGroovyCollections.min(java.util.Collection)
public static <T> T min(Iterator<T> self)
self
- an Iteratormin(java.util.Collection)
public static <T> T min(T[] self)
self
- an Object arraymin(java.util.Collection)
public static <T> T min(Collection<T> self, Comparator<T> comparator)
assert "hi" == ["hello","hi","hey"].min( { a, b -> a.length() <=> b.length() } as Comparator )
self
- a Collectioncomparator
- a Comparatorpublic static <T> T min(Iterator<T> self, Comparator<T> comparator)
self
- an Iteratorcomparator
- a Comparatormin(java.util.Collection, java.util.Comparator)
public static <T> T min(T[] self, Comparator<T> comparator)
self
- an Object arraycomparator
- a Comparatormin(java.util.Collection, java.util.Comparator)
public static <T> T min(Collection<T> self, Closure closure)
assert "hi" == ["hello","hi","hey"].min { it.length() }
def lastDigit = { a, b -> a % 10 <=> b % 10 } assert [19, 55, 91].min(lastDigit) == 91
def pets = ['dog', 'cat', 'anaconda'] def shortestName = pets.min{ it.size() } // one of 'dog' or 'cat' assert shortestName.size() == 3
self
- a Collectionclosure
- a 1 or 2 arg Closure used to determine the correct orderingpublic static <K,V> Map.Entry<K,V> min(Map<K,V> self, Closure closure)
def zoo = [monkeys:6, lions:5, tigers:7] def leastCommonEntry = zoo.min{ it.value } assert leastCommonEntry.value == 5 def mostCommonEntry = zoo.min{ a, b -> b.value <=> a.value } // double negative! assert mostCommonEntry.value == 7Edge case for multiple min values:
def zoo = [monkeys:6, lions:5, tigers:7] def lastCharOfName = { e -> e.key[-1] } def ans = zoo.min(lastCharOfName) // some random entry assert lastCharOfName(ans) == 's'
self
- a Mapclosure
- a 1 or 2 arg Closure used to determine the correct orderingpublic static <K,V> Map.Entry<K,V> max(Map<K,V> self, Closure closure)
def zoo = [monkeys:6, lions:5, tigers:7] def mostCommonEntry = zoo.max{ it.value } assert mostCommonEntry.value == 7 def leastCommonEntry = zoo.max{ a, b -> b.value <=> a.value } // double negative! assert leastCommonEntry.value == 5Edge case for multiple max values:
def zoo = [monkeys:6, lions:5, tigers:7] def lengthOfNamePlusNumber = { e -> e.key.size() + e.value } def ans = zoo.max(lengthOfNamePlusNumber) // one of [monkeys:6, tigers:7] assert lengthOfNamePlusNumber(ans) == 13
self
- a Mapclosure
- a 1 or 2 arg Closure used to determine the correct orderingpublic static <T> T min(Iterator<T> self, Closure closure)
self
- an Iteratorclosure
- a Closure used to determine the correct orderingmin(java.util.Collection, groovy.lang.Closure)
public static <T> T min(T[] self, Closure closure)
self
- an Object arrayclosure
- a Closure used to determine the correct orderingmin(java.util.Collection, groovy.lang.Closure)
public static <T> T max(Collection<T> self)
assert 5 == [2,3,1,5,4].max()
self
- a CollectionGroovyCollections.max(java.util.Collection)
public static <T> T max(Iterator<T> self)
self
- an IteratorGroovyCollections.max(java.util.Collection)
public static <T> T max(T[] self)
self
- an Object arraymax(java.util.Collection)
public static <T> T max(Collection<T> self, Closure closure)
assert "hello" == ["hello","hi","hey"].max { it.length() }
assert "hello" == ["hello","hi","hey"].max { a, b -> a.length() <=> b.length() }
def pets = ['dog', 'elephant', 'anaconda'] def longestName = pets.max{ it.size() } // one of 'elephant' or 'anaconda' assert longestName.size() == 8
self
- a Collectionclosure
- a 1 or 2 arg Closure used to determine the correct orderingpublic static <T> T max(Iterator<T> self, Closure closure)
self
- an Iteratorclosure
- a Closure used to determine the correct orderingmax(java.util.Collection, groovy.lang.Closure)
public static <T> T max(T[] self, Closure closure)
self
- an Object arrayclosure
- a Closure used to determine the correct orderingmax(java.util.Collection, groovy.lang.Closure)
public static <T> T max(Collection<T> self, Comparator<T> comparator)
assert "hello" == ["hello","hi","hey"].max( { a, b -> a.length() <=> b.length() } as Comparator )
self
- a Collectioncomparator
- a Comparatorpublic static <T> T max(Iterator<T> self, Comparator<T> comparator)
self
- an Iteratorcomparator
- a Comparatorpublic static <T> T max(T[] self, Comparator<T> comparator)
self
- an Object arraycomparator
- a Comparatorpublic static int size(Iterator self)
size()
method for Iterator
.
The iterator will become exhausted of elements after determining the size value.self
- an Iteratorpublic static int size(String text)
size()
method for String
.text
- a Stringpublic static int size(CharSequence text)
size()
method for CharSequence
.text
- a CharSequencepublic static int size(StringBuffer buffer)
size()
method for StringBuffer
.buffer
- a StringBufferpublic static long size(File self)
size()
method for File
.self
- a file objectpublic static long size(Matcher self)
size()
method for Matcher
.self
- a matcher objectpublic static int size(Object[] self)
size()
method for an array.self
- an Array of objectspublic static CharSequence getAt(CharSequence text, int index)
text
- a CharSequenceindex
- the index of the Character to getpublic static String getAt(String text, int index)
text
- a Stringindex
- the index of the Character to getpublic static CharSequence getAt(CharSequence text, Range range)
text
- a CharSequencerange
- a Rangepublic static CharSequence getAt(CharSequence text, IntRange range)
text
- a CharSequencerange
- an IntRangepublic static CharSequence getAt(CharSequence text, EmptyRange range)
text
- a CharSequencerange
- an EmptyRangepublic static String getAt(String text, IntRange range)
text
- a Stringrange
- an IntRangepublic static String getAt(String text, EmptyRange range)
text
- a Stringrange
- an EmptyRangepublic static String getAt(String text, Range range)
text
- a Stringrange
- a Rangepublic static String reverse(String self)
self
- a StringStringBuilder.reverse()
public static CharSequence reverse(CharSequence self)
self
- a CharSequencereverse(String)
public static String stripMargin(String self)
Strip leading whitespace/control characters followed by '|' from every line in a String.
assert 'ABC\n123\n456' == '''ABC |123 |456'''.stripMargin()
self
- The String to strip the margin fromstripMargin(String, char)
public static CharSequence stripMargin(CharSequence self)
Strip leading whitespace/control characters followed by '|' from every line in a CharSequence.
self
- The CharSequence to strip the margin fromstripMargin(CharSequence, char)
public static String stripMargin(String self, String marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a String.
self
- The String to strip the margin frommarginChar
- Any character that serves as margin delimiterstripMargin(String, char)
public static String stripMargin(CharSequence self, CharSequence marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a CharSequence.
self
- The CharSequence to strip the margin frommarginChar
- Any character that serves as margin delimiterstripMargin(String, String)
public static String stripMargin(String self, char marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a String.
assert 'ABC\n123\n456' == '''ABC *123 *456'''.stripMargin('*')
self
- The String to strip the margin frommarginChar
- Any character that serves as margin delimiterpublic static CharSequence stripMargin(CharSequence self, char marginChar)
Strip leading whitespace/control characters followed by marginChar from every line in a String.
self
- The CharSequence to strip the margin frommarginChar
- Any character that serves as margin delimiterstripMargin(String, char)
public static String stripIndent(String self)
Strip leading spaces from every line in a String. The line with the least number of leading spaces determines the number to remove. Lines only containing whitespace are ignored when calculating the number of leading spaces to strip.
assert ' A\n B\nC' == ' A\n B\n C'.stripIndent()
self
- The String to strip the leading spaces fromstripIndent(String, int)
public static CharSequence stripIndent(CharSequence self)
Strip leading spaces from every line in a CharSequence. The line with the least number of leading spaces determines the number to remove. Lines only containing whitespace are ignored when calculating the number of leading spaces to strip.
self
- The CharSequence to strip the leading spaces fromstripIndent(String)
public static boolean isAllWhitespace(String self)
self
- The String to check the characters inCharacter.isWhitespace(char)
public static boolean isAllWhitespace(CharSequence self)
self
- The CharSequence to check the characters inisAllWhitespace(String)
public static String stripIndent(String self, int numChars)
Strip numChar leading characters from every line in a String.
assert 'DEF\n456' == '''ABCDEF\n123456'''.stripIndent(3)
self
- The String to strip the characters fromnumChars
- The number of characters to strippublic static CharSequence stripIndent(CharSequence self, int numChars)
Strip numChar leading characters from every line in a CharSequence.
self
- The CharSequence to strip the characters fromnumChars
- The number of characters to strippublic static URL toURL(String self) throws MalformedURLException
self
- the String representing a URLMalformedURLException
- is thrown if the URL is not well formed.public static URL toURL(CharSequence self) throws MalformedURLException
self
- the CharSequence representing a URLMalformedURLException
- is thrown if the URL is not well formed.public static URI toURI(String self) throws URISyntaxException
self
- the String representing a URIURISyntaxException
- is thrown if the URI is not well formed.public static URI toURI(CharSequence self) throws URISyntaxException
self
- the CharSequence representing a URIURISyntaxException
- is thrown if the URI is not well formed.public static Pattern bitwiseNegate(String self)
self
- a String to convert into a regular expressionpublic static Pattern bitwiseNegate(CharSequence self)
self
- a String to convert into a regular expressionpublic static String replaceFirst(String self, Pattern pattern, String replacement)
Matcher.replaceFirst(java.lang.String)
.
Use Matcher.quoteReplacement(java.lang.String)
to suppress the special
meaning of these characters, if desired.
assert "foo".replaceFirst('o', 'X') == 'fXo'
self
- the string that is to be matchedpattern
- the regex Pattern to which the string of interest is to be matchedreplacement
- the string to be substituted for the first matchString.replaceFirst(java.lang.String, java.lang.String)
public static CharSequence replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement)
self
- the CharSequence that is to be matchedpattern
- the regex Pattern to which the CharSequence of interest is to be matchedreplacement
- the CharSequence to be substituted for the first matchreplaceFirst(String, Pattern, String)
public static String replaceAll(String self, Pattern pattern, String replacement)
Note that backslashes (\) and dollar signs ($) in the
replacement string may cause the results to be different than if it were
being treated as a literal replacement string; see
Matcher.replaceAll(java.lang.String)
.
Use Matcher.quoteReplacement(java.lang.String)
to suppress the special
meaning of these characters, if desired.
assert "foo".replaceAll('o', 'X') == 'fXX'
self
- the string that is to be matchedpattern
- the regex Pattern to which the string of interest is to be matchedreplacement
- the string to be substituted for the first matchString.replaceAll(java.lang.String, java.lang.String)
public static CharSequence replaceAll(CharSequence self, Pattern pattern, CharSequence replacement)
self
- the CharSequence that is to be matchedpattern
- the regex Pattern to which the CharSequence of interest is to be matchedreplacement
- the CharSequence to be substituted for the first matchreplaceAll(String, Pattern, String)
public static String tr(String self, String sourceSet, String replacementSet) throws ClassNotFoundException
assert 'hello'.tr('aeiou', 'AEIOU') == 'hEllO'A character range using regex-style syntax can also be used, e.g. here is an example which converts a word from lower to uppercase:
assert 'hello'.tr('a-z', 'A-Z') == 'HELLO'Hyphens at the start or end of sourceSet or replacementSet are treated as normal hyphens and are not considered to be part of a range specification. Similarly, a hyphen immediately after an earlier range is treated as a normal hyphen. So, '-x', 'x-' have no ranges while 'a-c-e' has the range 'a-c' plus the '-' character plus the 'e' character. Unlike the unix tr command, Groovy's tr command supports reverse ranges, e.g.:
assert 'hello'.tr('z-a', 'Z-A') == 'HELLO'If replacementSet is smaller than sourceSet, then the last character from replacementSet is used as the replacement for all remaining source characters as shown here:
assert 'Hello World!'.tr('a-z', 'A') == 'HAAAA WAAAA!'If sourceSet contains repeated characters, the last specified replacement is used as shown here:
assert 'Hello World!'.tr('lloo', '1234') == 'He224 W4r2d!'The functionality provided by tr can be achieved using regular expressions but tr provides a much more compact notation and efficient implementation for certain scenarios.
self
- the string that is to be translatedsourceSet
- the set of characters to translate fromreplacementSet
- the set of replacement charactersClassNotFoundException
StringUtil.tr(String, String, String)
public static CharSequence tr(CharSequence self, CharSequence sourceSet, CharSequence replacementSet) throws ClassNotFoundException
self
- the CharSequence that is to be translatedsourceSet
- the set of characters to translate fromreplacementSet
- the set of replacement charactersClassNotFoundException
tr(String, String, String)
public static boolean matches(String self, Pattern pattern)
self
- the string that is to be matchedpattern
- the regex Pattern to which the string of interest is to be matchedString.matches(java.lang.String)
public static boolean matches(CharSequence self, Pattern pattern)
self
- the CharSequence that is to be matchedpattern
- the regex Pattern to which the string of interest is to be matchedString.matches(java.lang.String)
public static String find(String self, String regex)
For example, if the regex doesn't match the result is null:
assert null == "New York, NY".find(/\d{5}/)
If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(/\d{5}/)
If we have capture groups in our expression, we still get back the full match
assert "10292-0098" == "New York, NY 10292-0098".find(/(\d{5})-?(\d{4})/)
self
- a Stringregex
- the capturing regexpublic static CharSequence find(CharSequence self, CharSequence regex)
self
- a CharSequenceregex
- the capturing regexfind(String, Pattern)
public static String find(String self, Pattern pattern)
For example, if the pattern doesn't match the result is null:
assert null == "New York, NY".find(~/\d{5}/)
If it does match, we get the matching string back:
assert "10292" == "New York, NY 10292-0098".find(~/\d{5}/)
If we have capture groups in our expression, the groups are ignored and we get back the full match:
assert "10292-0098" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/)If you need to work with capture groups, then use the closure version of this method or use Groovy's matcher operators or use eachMatch.
self
- a Stringpattern
- the compiled regex Patternpublic static CharSequence find(CharSequence self, Pattern pattern)
self
- a CharSequencepattern
- the compiled regex Patternfind(String, Pattern)
public static String find(String self, String regex, Closure closure)
For example, if the regex doesn't match, the result is null:
assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
If it does match and we don't have any capture groups in our regex, there is a single parameter on the closure that the match gets passed to:
assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
If we have capture groups in our expression, our closure has one parameter for the match, followed by one for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert match == "10292-0098" assert zip == "10292" assert plusFour == "0098" return zip }
If we have capture groups in our expression, and our closure has one parameter, the closure will be passed an array with the first element corresponding to the whole match, followed by an element for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert array[0] == "10292-0098" assert array[1] == "10292" assert array[2] == "0098" return array[1] }
If a capture group is optional, and doesn't match, then the corresponding value for that capture group passed to the closure will be null as illustrated here:
assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber -> assert "233-9999" == match assert null == areaCode assert "233" == exchange assert "9999" == stationNumber return "$exchange$stationNumber" }
self
- a Stringregex
- the capturing regex stringclosure
- the closure that will be passed the full match, plus each of the capturing groupspublic static CharSequence find(CharSequence self, CharSequence regex, Closure closure)
self
- a CharSequenceregex
- the capturing regex CharSequenceclosure
- the closure that will be passed the full match, plus each of the capturing groupsfind(String, Pattern, Closure)
public static String find(String self, Pattern pattern, Closure closure)
For example, if the pattern doesn't match, the result is null:
assert null == "New York, NY".find(~/\d{5}/) { match -> return "-$match-"}
If it does match and we don't have any capture groups in our regex, there is a single parameter on the closure that the match gets passed to:
assert "-10292-" == "New York, NY 10292-0098".find(~/\d{5}/) { match -> return "-$match-"}
If we have capture groups in our expression, our closure has one parameter for the match, followed by one for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert match == "10292-0098" assert zip == "10292" assert plusFour == "0098" return zip }
If we have capture groups in our expression, and our closure has one parameter, the closure will be passed an array with the first element corresponding to the whole match, followed by an element for each of the capture groups:
assert "10292" == "New York, NY 10292-0098".find(~/(\d{5})-?(\d{4})/) { match, zip, plusFour -> assert array[0] == "10292-0098" assert array[1] == "10292" assert array[2] == "0098" return array[1] }
If a capture group is optional, and doesn't match, then the corresponding value for that capture group passed to the closure will be null as illustrated here:
assert "2339999" == "adsf 233-9999 adsf".find(~/(\d{3})?-?(\d{3})-(\d{4})/) { match, areaCode, exchange, stationNumber -> assert "233-9999" == match assert null == areaCode assert "233" == exchange assert "9999" == stationNumber return "$exchange$stationNumber" }
self
- a Stringpattern
- the compiled regex Patternclosure
- the closure that will be passed the full match, plus each of the capturing groupspublic static CharSequence find(CharSequence self, Pattern pattern, Closure closure)
self
- a CharSequencepattern
- the compiled regex Patternclosure
- the closure that will be passed the full match, plus each of the capturing groupsfind(String, java.util.regex.Pattern, groovy.lang.Closure)
public static List<String> findAll(String self, String regex)
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/)
Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"] assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(/(\w*) Fish/)If you need to work with capture groups, then use the closure version of this method or use Groovy's matcher operators or use eachMatch.
self
- a Stringregex
- the capturing regex Stringpublic static List<CharSequence> findAll(CharSequence self, CharSequence regex)
self
- a CharSequenceregex
- the capturing regex CharSequencefindAll(String, String)
public static List<String> findAll(String self, Pattern pattern)
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/)
Any regular expression matches are returned in a list, and all regex capture groupings are ignored, only the full match is returned:
def expected = ["One Fish", "Two Fish", "Red Fish", "Blue Fish"] assert expected == "One Fish, Two Fish, Red Fish, Blue Fish".findAll(~/(\w*) Fish/)
self
- a Stringpattern
- the compiled regex Patternpublic static List<CharSequence> findAll(CharSequence self, Pattern pattern)
self
- a CharSequencepattern
- the compiled regex PatternfindAll(String, Pattern)
public static <T> List<T> findAll(String self, String regex, Closure<T> closure)
For example, if the regex doesn't match, it returns an empty list:
assert [] == "foo".findAll(/(\w*) Fish/) { match, firstWord -> return firstWord }
Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(/.ould/) { match -> "${match}n't"}
If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket" assert ["W > Wocket", "P > Pocket"] == orig.findAll(/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
self
- a Stringregex
- the capturing regex Stringclosure
- will be passed the full match plus each of the capturing groupspublic static <T> List<T> findAll(CharSequence self, CharSequence regex, Closure<T> closure)
self
- a CharSequenceregex
- the capturing regex CharSequenceclosure
- will be passed the full match plus each of the capturing groupsfindAll(String, String, Closure)
public static <T> List<T> findAll(String self, Pattern pattern, Closure<T> closure)
For example, if the pattern doesn't match, it returns an empty list:
assert [] == "foo".findAll(~/(\w*) Fish/) { match, firstWord -> return firstWord }
Any regular expression matches are passed to the closure, if there are no capture groups, there will be one parameter for the match:
assert ["couldn't", "wouldn't"] == "I could not, would not, with a fox.".findAll(~/.ould/) { match -> "${match}n't"}
If there are capture groups, the first parameter will be the match followed by one parameter for each capture group:
def orig = "There's a Wocket in my Pocket" assert ["W > Wocket", "P > Pocket"] == orig.findAll(~/(.)ocket/) { match, firstLetter -> "$firstLetter > $match" }
self
- a Stringpattern
- the compiled regex Patternclosure
- will be passed the full match plus each of the capturing groupspublic static <T> List<T> findAll(CharSequence self, Pattern pattern, Closure<T> closure)
self
- a CharSequencepattern
- the compiled regex Patternclosure
- will be passed the full match plus each of the capturing groupsfindAll(String, Pattern, Closure)
public static String replaceAll(String self, String regex, Closure closure)
For examples,
assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() } assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) Here, x is the global string of the matched group y is the first string in the matched group z is the second string in the matched group
Note that unlike String.replaceAll(String regex, String replacement), where the replacement string treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string and that value is used literally for the replacement.
self
- a Stringregex
- the capturing regexclosure
- the closure to apply on each captured groupPatternSyntaxException
- if the regular expression's syntax is invalidMatcher.quoteReplacement(java.lang.String)
,
replaceAll(String, Pattern, Closure)
public static CharSequence replaceAll(CharSequence self, CharSequence regex, Closure closure)
self
- a CharSequenceregex
- the capturing regexclosure
- the closure to apply on each captured groupPatternSyntaxException
- if the regular expression's syntax is invalidreplaceAll(String, Pattern, Closure)
public static CharSequence replaceAll(CharSequence self, CharSequence regex, CharSequence replacement)
self
- a CharSequenceregex
- the capturing regexreplacement
- the capturing regexPatternSyntaxException
- if the regular expression's syntax is invalidString.replaceAll(String, String)
public static String replaceFirst(String self, String regex, Closure closure)
For example (with some replaceAll variants thrown in for comparison purposes),
assert "hellO world" == "hello world".replaceFirst("(o)") { it[0].toUpperCase() } // first match assert "hellO wOrld" == "hello world".replaceAll("(o)") { it[0].toUpperCase() } // all matches assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
self
- a Stringregex
- the capturing regexclosure
- the closure to apply on the first captured groupPatternSyntaxException
- if the regular expression's syntax is invalidMatcher.quoteReplacement(java.lang.String)
,
replaceFirst(String, Pattern, Closure)
public static String replaceFirst(CharSequence self, CharSequence regex, CharSequence replacement)
self
- a CharSequenceregex
- the capturing regexreplacement
- the capturing regexPatternSyntaxException
- if the regular expression's syntax is invalidString.replaceAll(String, String)
public static String replaceFirst(CharSequence self, CharSequence regex, Closure closure)
self
- a CharSequenceregex
- the capturing regexclosure
- the closure to apply on the first captured groupPatternSyntaxException
- if the regular expression's syntax is invalidreplaceFirst(String, String, Closure)
public static String replaceAll(String self, Pattern pattern, Closure closure)
For examples,
assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOOBAR-FOOBAR-" == "foobar-FooBar-".replaceAll(~"(([fF][oO]{2})[bB]ar)", { Object[] it -> it[0].toUpperCase() }) Here, it[0] is the global string of the matched group it[1] is the first string in the matched group it[2] is the second string in the matched group assert "FOO-FOO-" == "foobar-FooBar-".replaceAll("(([fF][oO]{2})[bB]ar)", { x, y, z -> z.toUpperCase() }) Here, x is the global string of the matched group y is the first string in the matched group z is the second string in the matched group
Note that unlike String.replaceAll(String regex, String replacement), where the replacement string treats '$' and '\' specially (for group substitution), the result of the closure is converted to a string and that value is used literally for the replacement.
self
- a Stringpattern
- the capturing regex Patternclosure
- the closure to apply on each captured groupMatcher.quoteReplacement(java.lang.String)
public static String replaceAll(CharSequence self, Pattern pattern, Closure closure)
self
- a CharSequencepattern
- the capturing regex Patternclosure
- the closure to apply on each captured groupreplaceAll(String, Pattern, Closure)
public static String replaceFirst(String self, Pattern pattern, Closure closure)
For example (with some replaceAll variants thrown in for comparison purposes),
assert "hellO world" == "hello world".replaceFirst(~"(o)") { it[0].toUpperCase() } // first match assert "hellO wOrld" == "hello world".replaceAll(~"(o)") { it[0].toUpperCase() } // all matches assert '1-FISH, two fish' == "one fish, two fish".replaceFirst(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() } assert '1-FISH, 2-FISH' == "one fish, two fish".replaceAll(~/([a-z]{3})\s([a-z]{4})/) { [one:1, two:2][it[1]] + '-' + it[2].toUpperCase() }
self
- a Stringpattern
- the capturing regex Patternclosure
- the closure to apply on the first captured groupreplaceAll(String, Pattern, Closure)
public static String replaceFirst(CharSequence self, Pattern pattern, Closure closure)
self
- a CharSequencepattern
- the capturing regex Patternclosure
- the closure to apply on the first captured groupreplaceFirst(String, Pattern, Closure)
public static String padLeft(String self, Number numberOfChars, String padding)
println 'Numbers:' [1, 10, 100, 1000].each{ println it.toString().padLeft(5, '*') } [2, 20, 200, 2000].each{ println it.toString().padLeft(5, '*_') }will produce output like:
Numbers: ****1 ***10 **100 *1000 *_*_2 *_*20 *_200 *2000
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringpadding
- the characters used for paddingpublic static CharSequence padLeft(CharSequence self, Number numberOfChars, CharSequence padding)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingpadLeft(String, Number, String)
public static String padLeft(String self, Number numberOfChars)
println 'Numbers:' [1, 10, 100, 1000].each{ println it.toString().padLeft(5) }will produce output like:
Numbers: 1 10 100 1000
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringpadLeft(String, Number, String)
public static CharSequence padLeft(CharSequence self, Number numberOfChars)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadLeft(CharSequence, Number, CharSequence)
public static String padRight(String self, Number numberOfChars, String padding)
['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5, '#') + it.size() }will produce output like:
A####1 BB###2 CCC##3 DDDD#4
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringpadding
- the characters used for paddingpublic static CharSequence padRight(CharSequence self, Number numberOfChars, CharSequence padding)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingpadRight(String, Number, String)
public static String padRight(String self, Number numberOfChars)
['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5) + it.size() }will produce output like:
A 1 BB 2 CCC 3 DDDD 4
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringpublic static CharSequence padRight(CharSequence self, Number numberOfChars)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting stringpadRight(String, Number)
public static String center(String self, Number numberOfChars, String padding)
['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6, '+') + '|' }will produce output like:
|++A+++| |++BB++| |+CCC++| |+DDDD+|
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringpadding
- the characters used for paddingpublic static CharSequence center(CharSequence self, Number numberOfChars, CharSequence padding)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencepadding
- the characters used for paddingcenter(String, Number, String)
public static String center(String self, Number numberOfChars)
['A', 'BB', 'CCC', 'DDDD'].each{ println '|' + it.center(6) + '|' }will produce output like:
| A | | BB | | CCC | | DDDD |
self
- a String objectnumberOfChars
- the total minimum number of characters of the resulting stringcenter(String, Number, String)
public static CharSequence center(CharSequence self, Number numberOfChars)
self
- a CharSequence objectnumberOfChars
- the total minimum number of characters of the resulting CharSequencecenter(String, Number)
public static Object getAt(Matcher matcher, int idx)
def p = /ab[d|f]/ def m = "abcabdabeabf" =~ p assert 2 == m.count assert 2 == m.size() // synonym for m.getCount() assert ! m.hasGroup() assert 0 == m.groupCount() def matches = ["abd", "abf"] for (i in 0..<m.count) { assert m[i] == matches[i] }For an example using group matches,
def p = /(?:ab([c|d|e|f]))/ def m = "abcabdabeabf" =~ p assert 4 == m.count assert m.hasGroup() assert 1 == m.groupCount() def matches = [["abc", "c"], ["abd", "d"], ["abe", "e"], ["abf", "f"]] for (i in 0..<m.count) { assert m[i] == matches[i] }For another example using group matches,
def m = "abcabdabeabfabxyzabx" =~ /(?:ab([d|x-z]+))/ assert 3 == m.count assert m.hasGroup() assert 1 == m.groupCount() def matches = [["abd", "d"], ["abxyz", "xyz"], ["abx", "x"]] for (i in 0..<m.count) { assert m[i] == matches[i] }
matcher
- a Matcheridx
- an indexpublic static void setIndex(Matcher matcher, int idx)
matcher
- a Matcheridx
- the index numberpublic static int getCount(Matcher matcher)
matcher
- a Matcherpublic static boolean hasGroup(Matcher matcher)
matcher
- a Matchertrue
if matcher contains at least one group.public static <T> List<T> getAt(List<T> self, Range range)
def list = [1, "a", 4.5, true] assert list[1..2] == ["a", 4.5]
self
- a Listrange
- a Range indicating the items to getList.subList(int,int)
public static <T> List<T> getAt(List<T> self, EmptyRange range)
def list = [true, 1, 3.4] assert list[0..<0] == []
self
- a Listrange
- a Range indicating the items to getList.subList(int,int)
public static <T> List<T> getAt(List<T> self, Collection indices)
def list = [true, 1, 3.4, false] assert list[1,0,2] == [1, true, 3.4]
self
- a Listindices
- a Collection of indicespublic static <T> List<T> getAt(T[] self, Collection indices)
self
- an Array of Objectsindices
- a Collection of indicespublic static CharSequence getAt(CharSequence self, Collection indices)
self
- a CharSequenceindices
- a Collection of indicespublic static String getAt(String self, Collection indices)
self
- a Stringindices
- a Collection of indicespublic static List getAt(Matcher self, Collection indices)
self
- a Matcherindices
- a Collection of indicespublic static <K,V> Map<K,V> subMap(Map<K,V> map, Collection<K> keys)
assert [1:10, 2:20, 4:40].subMap( [2, 4] ) == [2:20, 4:40]
map
- a Mapkeys
- a Collection of keyspublic static <K,V> V get(Map<K,V> map, K key, V defaultValue)
def map=[:] map.get("a", []) << 5 assert map == [a:[5]]
map
- a Mapkey
- the key to lookup the value ofdefaultValue
- the value to return and add to the map for this key if
there is no entry for the given keypublic static <T> List<T> getAt(T[] array, Range range)
array
- an Array of Objectsrange
- a Rangepublic static <T> List<T> getAt(T[] array, IntRange range)
array
- an Array of Objectsrange
- an IntRangepublic static <T> List<T> getAt(T[] array, EmptyRange range)
array
- an Array of Objectsrange
- an EmptyRangepublic static <T> List<T> getAt(T[] array, ObjectRange range)
array
- an Array of Objectsrange
- an ObjectRangepublic static <T> List<T> toList(T[] array)
array
- an Array of Objectspublic static <T> T getAt(List<T> self, int idx)
def list = [2, "a", 5.3] assert list[1] == "a"
self
- a Listidx
- an indexpublic static <T> T getAt(Iterator<T> self, int idx)
def iter = [2, "a", 5.3].iterator() assert iter[1] == "a"A more elaborate example:
def items = [2, "a", 5.3] def iter = items.iterator() assert iter[-1] == 5.3 // iter exhausted, so reset iter = items.iterator() assert iter[1] == "a" // iter partially exhausted so now idx starts after "a" assert iter[0] == 5.3
self
- an Iteratoridx
- an index value (-self.size() <= idx < self.size())public static <T> void putAt(List<T> self, int idx, T value)
def list = [2, 3] list[0] = 1 assert list == [1, 3]
self
- a Listidx
- an indexvalue
- the value to put at the given indexpublic static void putAt(StringBuffer self, IntRange range, Object value)
self
- a StringBufferrange
- a Rangevalue
- the object that's toString() will be insertedpublic static void putAt(StringBuffer self, EmptyRange range, Object value)
self
- a StringBufferrange
- a Rangevalue
- the object that's toString() will be insertedpublic static void putAt(List self, EmptyRange range, Object value)
def list = ["a", true] list[1..<1] = 5 assert list == ["a", 5, true]
self
- a Listrange
- the (in this case empty) subset of the list to setvalue
- the values to put at the given sublist or a Collection of valuespublic static void putAt(List self, EmptyRange range, Collection value)
def list = ["a", true] list[1..<1] = [4, 3, 2] assert list == ["a", 4, 3, 2, true]
self
- a Listrange
- the (in this case empty) subset of the list to setvalue
- the Collection of valuesputAt(java.util.List, groovy.lang.EmptyRange, java.lang.Object)
public static void putAt(List self, IntRange range, Collection col)
def myList = [4, 3, 5, 1, 2, 8, 10] myList[3..5] = ["a", true] assert myList == [4, 3, 5, "a", true, 10]Items in the given range are replaced with items from the collection.
self
- a Listrange
- the subset of the list to setcol
- the collection of values to put at the given sublistpublic static void putAt(List self, IntRange range, Object value)
def myList = [4, 3, 5, 1, 2, 8, 10] myList[3..5] = "b" assert myList == [4, 3, 5, "b", 10]Items in the given range are replaced with the operand. The
value
operand is
always treated as a single value.self
- a Listrange
- the subset of the list to setvalue
- the value to put at the given sublistpublic static void putAt(List self, List splice, List values)
def list = ["a", true, 42, 9.4] list[1, 4] = ["x", false] assert list == ["a", "x", 42, 9.4, false]
self
- a Listsplice
- the subset of the list to setvalues
- the value to put at the given sublistpublic static void putAt(List self, List splice, Object value)
def list = ["a", true, 42, 9.4] list[1, 3] = 5 assert list == ["a", 5, 42, 5]
self
- a Listsplice
- the subset of the list to setvalue
- the value to put at the given sublistpublic static <K,V> V getAt(Map<K,V> self, K key)
def map = [a:10] assert map["a"] == 10
self
- a Mapkey
- an Object as a key for the mappublic static <K,V> Map<K,V> plus(Map<K,V> left, Map<K,V> right)
Map
containing all entries from left
and right
,
giving precedence to right
. Any keys appearing in both Maps
will appear in the resultant map with values from the right
operand. If the left
map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
Roughly equivalent to Map m = new HashMap(); m.putAll(left); m.putAll(right); return m;
but with some additional logic to preserve the left
Map type for common cases as
described above.
assert [a:10, b:20] + [a:5, c:7] == [a:5, b:20, c:7]
left
- a Mapright
- a Mappublic static <K,V> V putAt(Map<K,V> self, K key, V value)
self
- a Mapkey
- an Object as a key for the mapvalue
- the value to put into the mappublic static List getAt(Collection coll, String property)
assert [String, Long, Integer] == ["a",5L,2]["class"]
coll
- a Collectionproperty
- a Stringpublic static <K,V> Map<K,V> asImmutable(Map<? extends K,? extends V> self)
self
- a MapCollections.unmodifiableMap(java.util.Map)
public static <K,V> SortedMap<K,V> asImmutable(SortedMap<K,? extends V> self)
self
- a SortedMapCollections.unmodifiableSortedMap(java.util.SortedMap)
public static <T> List<T> asImmutable(List<? extends T> self)
self
- a ListCollections.unmodifiableList(java.util.List)
public static <T> Set<T> asImmutable(Set<? extends T> self)
self
- a SetCollections.unmodifiableSet(java.util.Set)
public static <T> SortedSet<T> asImmutable(SortedSet<T> self)
self
- a SortedSetCollections.unmodifiableSortedSet(java.util.SortedSet)
public static <T> Collection<T> asImmutable(Collection<? extends T> self)
def mutable = [1,2,3] def immutable = mutable.asImmutable() mutable << 4 try { immutable << 4 assert false } catch (UnsupportedOperationException) { assert true }
self
- a CollectionCollections.unmodifiableCollection(java.util.Collection)
public static <K,V> Map<K,V> asSynchronized(Map<K,V> self)
self
- a MapCollections.synchronizedMap(java.util.Map)
public static <K,V> SortedMap<K,V> asSynchronized(SortedMap<K,V> self)
self
- a SortedMapCollections.synchronizedSortedMap(java.util.SortedMap)
public static <T> Collection<T> asSynchronized(Collection<T> self)
self
- a CollectionCollections.synchronizedCollection(java.util.Collection)
public static <T> List<T> asSynchronized(List<T> self)
self
- a ListCollections.synchronizedList(java.util.List)
public static <T> Set<T> asSynchronized(Set<T> self)
self
- a SetCollections.synchronizedSet(java.util.Set)
public static <T> SortedSet<T> asSynchronized(SortedSet<T> self)
self
- a SortedSetCollections.synchronizedSortedSet(java.util.SortedSet)
public static SpreadMap spread(Map self)
toSpreadMap(java.util.Map)
.self
- a mappublic static SpreadMap toSpreadMap(Map self)
SpreadMap
from this map.
The example below shows the various possible use cases:
def fn(Map m) { return m.a + m.b + m.c + m.d } assert fn(a:1, b:2, c:3, d:4) == 10 assert fn(a:1, *:[b:2, c:3], d:4) == 10 assert fn([a:1, b:2, c:3, d:4].toSpreadMap()) == 10 assert fn((['a', 1, 'b', 2, 'c', 3, 'd', 4] as Object[]).toSpreadMap()) == 10 assert fn(['a', 1, 'b', 2, 'c', 3, 'd', 4].toSpreadMap()) == 10 assert fn(['abcd'.toList(), 1..4].transpose().flatten().toSpreadMap()) == 10Note that toSpreadMap() is not normally used explicitly but under the covers by Groovy.
self
- a map to be converted into a SpreadMapSpreadMap.SpreadMap(java.util.Map)
public static SpreadMap toSpreadMap(Object[] self)
self
- an object arraySpreadMap.SpreadMap(java.lang.Object[])
,
toSpreadMap(java.util.Map)
public static SpreadMap toSpreadMap(List self)
self
- a listSpreadMap.SpreadMap(java.util.List)
,
toSpreadMap(java.util.Map)
public static <K,V> Map<K,V> withDefault(Map<K,V> self, Closure init)
get(key)
. If an unknown key is found, a default value will be
stored into the Map before being returned. The default value stored will be the
result of calling the supplied Closure with the key as the parameter to the Closure.
Example usage:
def map = [a:1, b:2].withDefault{ k -> k.toCharacter().isLowerCase() ? 10 : -10 } def expected = [a:1, b:2, c:10, D:-10] assert expected.every{ e -> e.value == map[e.key] } def constMap = [:].withDefault{ 42 } assert constMap.foo == 42 assert constMap.size() == 1
self
- a Mapinit
- a Closure which is passed the unknown keypublic static <T> List<T> sort(Collection<T> self)
assert [1,2,3] == [3,1,2].sort()
self
- the collection to be sortedsort(Collection, boolean)
public static <T> List<T> sort(Collection<T> self, boolean mutate)
assert [1,2,3] == [3,1,2].sort()
def orig = [1, 3, 2] def sorted = orig.sort(false) assert orig == [1, 3, 2] assert sorted == [1, 2, 3]
self
- the collection to be sortedmutate
- false will always cause a new list to be created, true will mutate lists in placepublic static <K,V> Map<K,V> sort(Map<K,V> self, Closure closure)
def map = [a:5, b:3, c:6, d:4].sort { a, b -> a.value <=> b.value } assert map == [b:3, d:4, a:5, c:6]
self
- the original unsorted mapclosure
- a Closure used as a comparatorpublic static <K,V> Map<K,V> sort(Map<K,V> self, Comparator<K> comparator)
def map = [ba:3, cz:6, ab:5].sort({ a, b -> a[-1] <=> b[-1] } as Comparator) assert map*.value == [3, 5, 6]
self
- the original unsorted mapcomparator
- a Comparatorpublic static <K,V> Map<K,V> sort(Map<K,V> self)
map = [ba:3, cz:6, ab:5].sort() assert map*.value == [5, 3, 6]
self
- the original unsorted mappublic static <T> T[] sort(T[] self)
self
- the array to be sortedpublic static <T> T[] sort(T[] self, boolean mutate)
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false) assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["Hey","hello","hi"] as String[] orig.sort(true) assert orig == ["Hey","hello","hi"] as String[]
self
- the array to be sortedmutate
- false will always cause a new array to be created, true will mutate the array in placepublic static <T> Iterator<T> sort(Iterator<T> self)
self
- the Iterator to be sortedpublic static <T> Iterator<T> sort(Iterator<T> self, Comparator<T> comparator)
self
- the Iterator to be sortedcomparator
- a Comparator used for comparing itemspublic static <T> List<T> sort(Collection<T> self, Comparator<T> comparator)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
assert ["hello","Hey","hi"] == ["hello","hi","Hey"].sort(String.CASE_INSENSITIVE_ORDER)
self
- a collection to be sortedcomparator
- a Comparator used for the comparisonsort(Collection, boolean, Comparator)
public static <T> List<T> sort(Collection<T> self, boolean mutate, Comparator<T> comparator)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
def orig = ["hello","hi","Hey"] def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","hi","Hey"] assert sorted == ["hello","Hey","hi"]
self
- a collection to be sortedmutate
- false will always cause a new list to be created, true will mutate lists in placecomparator
- a Comparator used for the comparisonpublic static <T> T[] sort(T[] self, Comparator<T> comparator)
self
- the array to be sortedcomparator
- a Comparator used for the comparisonpublic static <T> T[] sort(T[] self, boolean mutate, Comparator<T> comparator)
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["hello","Hey","hi"] as String[] orig.sort(true, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","Hey","hi"] as String[]
self
- the array containing elements to be sortedmutate
- false will always cause a new array to be created, true will mutate arrays in placecomparator
- a Comparator used for the comparisonpublic static <T> Iterator<T> sort(Iterator<T> self, Closure closure)
self
- the Iterator to be sortedclosure
- a Closure used to determine the correct orderingpublic static <T> T[] sort(T[] self, Closure closure)
self
- the array containing the elements to be sortedclosure
- a Closure used to determine the correct orderingpublic static <T> T[] sort(T[] self, boolean mutate, Closure closure)
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false) { it.size() } assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["hi","Hey","hello"] as String[] orig.sort(true) { it.size() } assert orig == ["hi","Hey","hello"] as String[]
self
- the array to be sortedmutate
- false will always cause a new array to be created, true will mutate arrays in placeclosure
- a Closure used to determine the correct orderingpublic static <T> List<T> sort(Collection<T> self, Closure closure)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
self
- a Collection to be sortedclosure
- a 1 or 2 arg Closure used to determine the correct orderingsort(Collection, boolean, Closure)
public static <T> List<T> sort(Collection<T> self, boolean mutate, Closure closure)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
def orig = ["hello","hi","Hey"] def sorted = orig.sort(false) { it.toUpperCase() } assert orig == ["hello","hi","Hey"] assert sorted == ["hello","Hey","hi"]
self
- a Collection to be sortedmutate
- false will always cause a new list to be created, true will mutate lists in placeclosure
- a 1 or 2 arg Closure used to determine the correct orderingpublic static <T> SortedSet<T> sort(SortedSet<T> self)
self
- an already sorted setpublic static <K,V> SortedMap<K,V> sort(SortedMap<K,V> self)
self
- an already sorted mappublic static <T> T pop(List<T> self)
def list = ["a", false, 2] assert list.pop() == 2 assert list == ["a", false]
self
- a ListNoSuchElementException
- if the list is empty and you try to pop() it.public static <K,V> Map<K,V> putAll(Map<K,V> self, Collection<Map.Entry<K,V>> entries)
self
- a Mapentries
- a Collection of Map.Entry items to be added to the Map.public static <K,V> Map<K,V> plus(Map<K,V> self, Collection<Map.Entry<K,V>> entries)
Map
containing all entries from self
and entries
,
giving precedence to entries
. Any keys appearing in both Maps
will appear in the resultant map with values from the entries
operand. If self
map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
self
- a Mapentries
- a Collection of Map.Entry items to be added to the Map.public static <T> boolean push(List<T> self, T value)
def list = [3, 4, 2] list.push("x") assert list == [3, 4, 2, "x"]
self
- a Listvalue
- element to be appended to this list.NoSuchElementException
- if the list is empty and you try to pop() it.public static <T> T last(List<T> self)
def list = [3, 4, 2] assert list.last() == 2 assert list == [3, 4, 2]
self
- a ListNoSuchElementException
- if the list is empty and you try to access the last() item.public static <T> T last(T[] self)
def array = [3, 4, 2].toArray() assert array.last() == 2
self
- an ObjectArrayNoSuchElementException
- if the array is empty and you try to access the last() item.public static <T> T first(List<T> self)
def list = [3, 4, 2] assert list.first() == 3 assert list == [3, 4, 2]
self
- a ListNoSuchElementException
- if the list is empty and you try to access the first() item.public static <T> T first(T[] self)
def array = [3, 4, 2].toArray() assert array.first() == 3
self
- an Object arrayNoSuchElementException
- if the array is empty and you try to access the first() item.public static <T> T head(List<T> self)
def list = [3, 4, 2] assert list.head() == 3 assert list == [3, 4, 2]
self
- a ListNoSuchElementException
- if the list is empty and you try to access the head() item.public static <T> T head(T[] self)
def array = [3, 4, 2].toArray() assert array.head() == 3
self
- an Object arrayNoSuchElementException
- if the array is empty and you try to access the head() item.public static <T> List<T> tail(List<T> self)
def list = [3, 4, 2] assert list.tail() == [4, 2] assert list == [3, 4, 2]
self
- a ListNoSuchElementException
- if the list is empty and you try to access the tail() item.public static <T> T[] tail(T[] self)
String[] strings = ["a", "b", "c"] def result = strings.tail() assert strings.class.componentType == String
self
- an Object arrayNoSuchElementException
- if the list is empty and you try to access the tail() item.public static <T> List<T> take(List<T> self, int num)
num
elements from the head of this list.
def strings = [ 'a', 'b', 'c' ] assert strings.take( 0 ) == [] assert strings.take( 2 ) == [ 'a', 'b' ] assert strings.take( 5 ) == [ 'a', 'b', 'c' ]
self
- the original listnum
- the number of elements to take from this listnum
elements of this list,
or else the whole list if it has less then num
elements.public static <T> T[] take(T[] self, int num)
num
elements from the head of this array.
String[] strings = [ 'a', 'b', 'c' ] assert strings.take( 0 ) == [] as String[] assert strings.take( 2 ) == [ 'a', 'b' ] as String[] assert strings.take( 5 ) == [ 'a', 'b', 'c' ] as String[]
self
- the original arraynum
- the number of elements to take from this arraynum
elements of this array,
or else the whole array if it has less then num
elements.public static <K,V> Map<K,V> take(Map<K,V> self, int num)
num
elements from the head of this map.
If the map instance does not have ordered keys,then this function could return a random n
entries. Groovy by default used LinkedHashMap, so this shouldn't be an issue in the main.
def strings = [ 'a':10, 'b':20, 'c':30 ]
assert strings.take( 0 ) == [:]
assert strings.take( 2 ) == [ 'a':10, 'b':20 ]
assert strings.take( 5 ) == [ 'a':10, 'b':20, 'c':30 ]
self
- the original mapnum
- the number of elements to take from this mapnum
elements of this map,
or else the whole map if it has less then num
elements.public static <T> Iterator<T> take(Iterator<T> self, int num)
num
elements from this iterator.
The original iterator is stepped along by num
elements.
def a = 0 def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator def iteratorCompare( Iterator a, List b ) { a.collect { it } == b } assert iteratorCompare( iter.take( 0 ), [] ) assert iteratorCompare( iter.take( 2 ), [ 0, 1 ] ) assert iteratorCompare( iter.take( 5 ), [ 2, 3, 4, 5, 6 ] )
self
- the Iteratornum
- the number of elements to take from this iteratornum
elements of this iterator.public static CharSequence take(CharSequence self, int num)
num
elements from this CharSequence.
def text = "Groovy" assert text.take( 0 ) == '' assert text.take( 2 ) == 'Gr' assert text.take( 7 ) == 'Groovy'
self
- the original CharSequencenum
- the number of chars to take from this CharSequencenum
chars,
or else the whole CharSequence if it has less then num
elements.public static <T> List<T> drop(List<T> self, int num)
def strings = [ 'a', 'b', 'c' ] assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] assert strings.drop( 2 ) == [ 'c' ] assert strings.drop( 5 ) == []
self
- the original listnum
- the number of elements to drop from this listnum
ones, or else the empty list, if this list has
less than num
elements.public static <T> T[] drop(T[] self, int num)
String[] strings = [ 'a', 'b', 'c' ] assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] as String[] assert strings.drop( 2 ) == [ 'c' ] as String[] assert strings.drop( 5 ) == [] as String[]
self
- the original arraynum
- the number of elements to drop from this arraynum
ones, or else the empty array, if this
array has less than num
elements.public static <K,V> Map<K,V> drop(Map<K,V> self, int num)
n
entries. Groovy by default used LinkedHashMap, so this shouldn't be an issue in the main.
def strings = [ 'a':10, 'b':20, 'c':30 ]
assert strings.drop( 0 ) == [ 'a':10, 'b':20, 'c':30 ]
assert strings.drop( 2 ) == [ 'c':30 ]
assert strings.drop( 5 ) == [:]
self
- the original mapnum
- the number of elements to drop from this mapnum
ones, or else the empty map, if this map has
less than num
elements.public static <T> Iterator<T> drop(Iterator<T> self, int num)
num
elements.
def iteratorCompare( Iterator a, List b ) { a.collect { it } == b } def iter = [ 1, 2, 3, 4, 5 ].listIterator() assert iteratorCompare( iter.drop( 0 ), [ 1, 2, 3, 4, 5 ] ) iter = [ 1, 2, 3, 4, 5 ].listIterator() assert iteratorCompare( iter.drop( 2 ), [ 3, 4, 5 ] ) iter = [ 1, 2, 3, 4, 5 ].listIterator() assert iteratorCompare( iter.drop( 5 ), [] )
self
- the original iteratornum
- the number of elements to drop from this iteratornum
elements if they exist.public static CharSequence drop(CharSequence self, int num)
def text = "Groovy" assert text.drop( 0 ) == 'Groovy' assert text.drop( 2 ) == 'oovy' assert text.drop( 7 ) == ''
self
- the original CharSequencenum
- the number of characters to drop from this iteratornum
ones,
or else an empty String, if this CharSequence has less than num
characters.public static <T> List<T> asList(Collection<T> self)
Example usage:
assert new HashSet().asList() instanceof List
self
- a collection to be converted into a Listpublic static boolean asBoolean(Object object)
object
- the object to coercepublic static boolean asBoolean(Boolean bool)
bool
- the Booleanpublic static boolean asBoolean(Matcher matcher)
matcher
- the matcherpublic static boolean asBoolean(Collection collection)
assert [1,2].asBoolean() == true
assert [].asBoolean() == false
collection
- the collectionpublic static boolean asBoolean(Map map)
assert [:] as Boolean == false assert [a:2] as Boolean == true
map
- the mappublic static boolean asBoolean(Iterator iterator)
iterator
- the iteratorpublic static boolean asBoolean(Enumeration enumeration)
enumeration
- the enumerationpublic static boolean asBoolean(CharSequence string)
string
- the character sequencepublic static boolean asBoolean(Object[] array)
array
- the arraypublic static boolean asBoolean(byte[] array)
array
- an arraypublic static boolean asBoolean(short[] array)
array
- an arraypublic static boolean asBoolean(int[] array)
array
- an arraypublic static boolean asBoolean(long[] array)
array
- an arraypublic static boolean asBoolean(float[] array)
array
- an arraypublic static boolean asBoolean(double[] array)
array
- an arraypublic static boolean asBoolean(boolean[] array)
array
- an arraypublic static boolean asBoolean(char[] array)
array
- an arraypublic static boolean asBoolean(Character character)
character
- the characterpublic static boolean asBoolean(Number number)
number
- the numberpublic static <T> T asType(Collection col, Class<T> clazz)
col
- a collectionclazz
- the desired classasType(java.lang.Object, java.lang.Class)
public static <T> T asType(Object[] ary, Class<T> clazz)
ary
- an arrayclazz
- the desired classasType(java.lang.Object, java.lang.Class)
public static <T> T asType(Closure cl, Class<T> clazz)
cl
- the implementation of the single methodclazz
- the target typepublic static <T> T asType(Map map, Class<T> clazz)
map
- this mapclazz
- the target typepublic static <T> List<T> reverse(List<T> self)
def list = ["a", 4, false] assert list.reverse() == [false, 4, "a"] assert list == ["a", 4, false]
self
- a Listreverse(List, boolean)
public static <T> List<T> reverse(List<T> self, boolean mutate)
def list = ["a", 4, false] assert list.reverse(false) == [false, 4, "a"] assert list == ["a", 4, false] assert list.reverse(true) == [false, 4, "a"] assert list == [false, 4, "a"]
self
- a Listmutate
- true if the list itself should be reversed in place and returned, false if a new list should be createdpublic static <T> T[] reverse(T[] self)
self
- an arrayreverse(Object[], boolean)
public static <T> T[] reverse(T[] self, boolean mutate)
self
- an arraymutate
- true if the array itself should be reversed in place and returned, false if a new array should be createdpublic static <T> Iterator<T> reverse(Iterator<T> self)
self
- an Iteratorpublic static <T> Collection<T> plus(Collection<T> left, Collection<T> right)
assert [1,2,3,4] == [1,2] + [3,4]
left
- the left Collectionright
- the right Collectionpublic static <T> List<T> plus(List<T> self, int index, T[] items)
def items = [1, 2, 3] def newItems = items.plus(2, 'a'..'c' as String[]) assert newItems == [1, 2, 'a', 'b', 'c', 3] assert items == [1, 2, 3]See also
addAll
for similar functionality with modify semantics, i.e. which performs
the changes on the original list itself.self
- an original listitems
- array containing elements to be merged with elements from the original listindex
- index at which to insert the first element from the specified arrayplus(List, int, List)
public static <T> List<T> plus(List<T> self, int index, List<T> additions)
def items = [1, 2, 3] def newItems = items.plus(2, 'a'..'c') assert newItems == [1, 2, 'a', 'b', 'c', 3] assert items == [1, 2, 3]See also
addAll
for similar functionality with modify semantics, i.e. which performs
the changes on the original list itself.self
- an original listadditions
- array containing elements to be merged with elements from the original listindex
- index at which to insert the first element from the specified listpublic static <T> Collection<T> plus(Collection<T> left, T right)
assert [1,2,3] == [1,2] + 3
left
- a Collectionright
- an object to add/appendpublic static <T> List<T> multiply(Collection<T> self, Number factor)
assert [1,2,3,1,2,3] == [1,2,3] * 2
self
- a Collectionfactor
- the number of times to appendpublic static <T> Collection<T> intersect(Collection<T> left, Collection<T> right)
assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])
left
- a Collectionright
- a Collectionpublic static <K,V> Map<K,V> intersect(Map<K,V> left, Map<K,V> right)
assert [4:4,5:5] == [1:1,2:2,3:3,4:4,5:5].intersect([4:4,5:5,6:6,7:7,8:8])
assert [1: 1, 2: 2, 3: 3, 4: 4].intersect( [1: 1.0, 2: 2, 5: 5] ) == [1:1, 2:2]
left
- a mapright
- a mappublic static boolean disjoint(Collection left, Collection right)
true
if the intersection of two collections is empty.
assert [1,2,3].disjoint([3,4,5]) == false
assert [1,2].disjoint([3,4]) == true
left
- a Collectionright
- a Collectiontrue
if the intersection of two collections
is empty, false
otherwise.public static boolean equals(int[] left, int[] right)
left
- an int arrayright
- the operand array.public static boolean equals(Object[] left, List right)
false
if either collection is null
.left
- this arrayright
- the list being comparedpublic static boolean equals(List left, Object[] right)
false
if either collection is null
.
assert [1, "a"].equals( [ 1, "a" ] as Object[] )
left
- this Listright
- this Object[] being compared topublic static boolean equals(List left, List right)
null
, the result
is true; otherwise if either list is null
, the result
is false
.
assert ["a", 2].equals(["a", 2]) assert ![2, "a"].equals("a", 2) assert [2.0, "a"].equals(2L, "a") // number comparison at work
left
- this Listright
- the List being compared to.true
if the contents of both lists are identical,
false
otherwise.public static <T> boolean equals(Set<T> self, Set<T> other)
null
, the result
is true; otherwise if either set is null
, the result
is false
. Example usage:
Set s1 = ["a", 2] def s2 = [2, 'a'] as Set Set s3 = [3, 'a'] def s4 = [2.0, 'a'] as Set def s5 = [2L, 'a'] as Set assert s1.equals(s2) assert !s1.equals(s3) assert s1.equals(s4) assert s1.equals(s5)
self
- this Setother
- the Set being compared topublic static boolean equals(Map self, Map other)
Example usage:
assert [a:2, b:3] == [a:2L, b:3.0]
self
- this Mapother
- the Map being compared topublic static <T> Set<T> minus(Set<T> self, Collection operands)
self
- a set objectoperands
- the items to remove from the setpublic static <T> Set<T> minus(Set<T> self, Object operand)
self
- a set objectoperand
- the operand to remove from the setpublic static <T> T[] minus(T[] self, Collection<T> removeMe)
self
- an object arrayremoveMe
- a Collection of elements to removepublic static <T> T[] minus(T[] self, T[] removeMe)
self
- an object arrayremoveMe
- an array of elements to removepublic static <T> List<T> minus(List<T> self, Collection<T> removeMe)
assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]
self
- a ListremoveMe
- a Collection of elements to removepublic static <T> List<T> minus(List<T> self, Object operand)
assert ["a", 5, 5, true] - 5 == ["a", true]
self
- a List objectoperand
- an element to remove from the listpublic static <T> T[] minus(T[] self, Object operand)
self
- an object arrayoperand
- an element to remove from the arraypublic static <K,V> Map<K,V> minus(Map<K,V> self, Map<K,V> operands)
self
- a map objectoperands
- the entries to remove from the mappublic static Collection<?> flatten(Collection<?> self)
assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()
self
- a Collection to flattenpublic static Collection flatten(Object[] self)
self
- an Array to flattenpublic static Collection flatten(boolean[] self)
self
- a boolean Array to flattenpublic static Collection flatten(byte[] self)
self
- a byte Array to flattenpublic static Collection flatten(char[] self)
self
- a char Array to flattenpublic static Collection flatten(short[] self)
self
- a short Array to flattenpublic static Collection flatten(int[] self)
self
- an int Array to flattenpublic static Collection flatten(long[] self)
self
- a long Array to flattenpublic static Collection flatten(float[] self)
self
- a float Array to flattenpublic static Collection flatten(double[] self)
self
- a double Array to flattenpublic static <T> Collection<T> flatten(Collection<T> self, Closure<? extends T> flattenUsing)
self
- a CollectionflattenUsing
- a closure to determine how to flatten non-Array, non-Collection elementspublic static <T> Collection<T> leftShift(Collection<T> self, T value)
def list = [1,2] list << 3 assert list == [1,2,3]
self
- a Collectionvalue
- an Object to be added to the collection.public static <T> BlockingQueue<T> leftShift(BlockingQueue<T> self, T value) throws InterruptedException
def list = new java.util.concurrent.LinkedBlockingQueue () list << 3 << 2 << 1 assert list.iterator().collect{it} == [3,2,1]
self
- a Collectionvalue
- an Object to be added to the collection.InterruptedException
public static <K,V> Map<K,V> leftShift(Map<K,V> self, Map.Entry<K,V> entry)
self
- a Mapentry
- a Map.Entry to be added to the Map.public static <K,V> Map<K,V> leftShift(Map<K,V> self, Map<K,V> other)
map1 << map2
; otherwise it's just a synonym for
putAll
though it returns the original map rather than
being a void
method. Example usage:
def map = [a:1, b:2] map << [c:3, d:4] assert map == [a:1, b:2, c:3, d:4]
self
- a Mapother
- another Map whose entries should be added to the original Map.public static StringBuffer leftShift(String self, Object value)
self
- a Stringvalue
- an Objectpublic static StringBuilder leftShift(CharSequence self, Object value)
self
- a CharSequencevalue
- an Objectpublic static StringBuilder leftShift(StringBuilder self, Object value)
self
- a StringBuildervalue
- an Objectprotected static StringWriter createStringWriter(String self)
protected static StringBufferWriter createStringBufferWriter(StringBuffer self)
public static StringBuffer leftShift(StringBuffer self, Object value)
self
- a StringBuffervalue
- a value to appendpublic static Writer leftShift(Writer self, Object value) throws IOException
self
- a Writervalue
- a value to appendIOException
- if an I/O error occurs.public static Number leftShift(Number self, Number operand)
self
- a Number objectoperand
- the shift distance by which to left shift the numberpublic static Number rightShift(Number self, Number operand)
self
- a Number objectoperand
- the shift distance by which to right shift the numberpublic static Number rightShiftUnsigned(Number self, Number operand)
self
- a Number objectoperand
- the shift distance by which to right shift (unsigned) the numberpublic static void write(Writer self, Writable writable) throws IOException
self
- a Writerwritable
- an object implementing the Writable interfaceIOException
- if an I/O error occurs.public static Writer leftShift(OutputStream self, Object value) throws IOException
self
- an OutputStreamvalue
- a value to appendIOException
- if an I/O error occurs.public static void leftShift(ObjectOutputStream self, Object value) throws IOException
self
- an ObjectOutputStreamvalue
- an object to write to the streamIOException
- if an I/O error occurs.public static OutputStream leftShift(OutputStream self, InputStream in) throws IOException
self
- stream on which to writein
- stream to read fromIOException
- if an I/O error occurs.public static OutputStream leftShift(OutputStream self, byte[] value) throws IOException
self
- an OutputStreamvalue
- a value to appendIOException
- if an I/O error occurs.public static List<Byte> getAt(byte[] array, Range range)
array
- a byte arrayrange
- a range indicating the indices for the items to retrievepublic static List<Character> getAt(char[] array, Range range)
array
- a char arrayrange
- a range indicating the indices for the items to retrievepublic static List<Short> getAt(short[] array, Range range)
array
- a short arrayrange
- a range indicating the indices for the items to retrievepublic static List<Integer> getAt(int[] array, Range range)
array
- an int arrayrange
- a range indicating the indices for the items to retrievepublic static List<Long> getAt(long[] array, Range range)
array
- a long arrayrange
- a range indicating the indices for the items to retrievepublic static List<Float> getAt(float[] array, Range range)
array
- a float arrayrange
- a range indicating the indices for the items to retrievepublic static List<Double> getAt(double[] array, Range range)
array
- a double arrayrange
- a range indicating the indices for the items to retrievepublic static List<Boolean> getAt(boolean[] array, Range range)
array
- a boolean arrayrange
- a range indicating the indices for the items to retrievepublic static List<Byte> getAt(byte[] array, IntRange range)
array
- a byte arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Character> getAt(char[] array, IntRange range)
array
- a char arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Short> getAt(short[] array, IntRange range)
array
- a short arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Integer> getAt(int[] array, IntRange range)
array
- an int arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Long> getAt(long[] array, IntRange range)
array
- a long arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Float> getAt(float[] array, IntRange range)
array
- a float arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Double> getAt(double[] array, IntRange range)
array
- a double arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Boolean> getAt(boolean[] array, IntRange range)
array
- a boolean arrayrange
- an IntRange indicating the indices for the items to retrievepublic static List<Byte> getAt(byte[] array, ObjectRange range)
array
- a byte arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Character> getAt(char[] array, ObjectRange range)
array
- a char arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Short> getAt(short[] array, ObjectRange range)
array
- a short arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Integer> getAt(int[] array, ObjectRange range)
array
- an int arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Long> getAt(long[] array, ObjectRange range)
array
- a long arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Float> getAt(float[] array, ObjectRange range)
array
- a float arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Double> getAt(double[] array, ObjectRange range)
array
- a double arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Boolean> getAt(boolean[] array, ObjectRange range)
array
- a byte arrayrange
- an ObjectRange indicating the indices for the items to retrievepublic static List<Byte> getAt(byte[] array, Collection indices)
array
- a byte arrayindices
- a collection of indices for the items to retrievepublic static List<Character> getAt(char[] array, Collection indices)
array
- a char arrayindices
- a collection of indices for the items to retrievepublic static List<Short> getAt(short[] array, Collection indices)
array
- a short arrayindices
- a collection of indices for the items to retrievepublic static List<Integer> getAt(int[] array, Collection indices)
array
- an int arrayindices
- a collection of indices for the items to retrievepublic static List<Long> getAt(long[] array, Collection indices)
array
- a long arrayindices
- a collection of indices for the items to retrievepublic static List<Float> getAt(float[] array, Collection indices)
array
- a float arrayindices
- a collection of indices for the items to retrievepublic static List<Double> getAt(double[] array, Collection indices)
array
- a double arrayindices
- a collection of indices for the items to retrievepublic static List<Boolean> getAt(boolean[] array, Collection indices)
array
- a boolean arrayindices
- a collection of indices for the items to retrievepublic static boolean getAt(BitSet self, int index)
self
- a BitSetindex
- index to retrieveBitSet
public static BitSet getAt(BitSet self, IntRange range)
public static void putAt(BitSet self, IntRange range, boolean value)
public static void putAt(BitSet self, int index, boolean value)
self
- a BitSetindex
- index of the entry to setvalue
- valueBitSet
public static int size(boolean[] array)
array
- a boolean arrayArray.getLength(java.lang.Object)
public static int size(byte[] array)
array
- a byte arrayArray.getLength(java.lang.Object)
public static int size(char[] array)
array
- a char arrayArray.getLength(java.lang.Object)
public static int size(short[] array)
array
- a short arrayArray.getLength(java.lang.Object)
public static int size(int[] array)
array
- an int arrayArray.getLength(java.lang.Object)
public static int size(long[] array)
array
- a long arrayArray.getLength(java.lang.Object)
public static int size(float[] array)
array
- a float arrayArray.getLength(java.lang.Object)
public static int size(double[] array)
array
- a double arrayArray.getLength(java.lang.Object)
public static List<Byte> toList(byte[] array)
array
- a byte arraypublic static List<Boolean> toList(boolean[] array)
array
- a boolean arraypublic static List<Character> toList(char[] array)
array
- a char arraypublic static List<Short> toList(short[] array)
array
- a short arraypublic static List<Integer> toList(int[] array)
array
- an int arraypublic static List<Long> toList(long[] array)
array
- a long arraypublic static List<Float> toList(float[] array)
array
- a float arraypublic static List<Double> toList(double[] array)
array
- a double arraypublic static Set<Byte> toSet(byte[] array)
array
- a byte arraypublic static Set<Boolean> toSet(boolean[] array)
array
- a boolean arraypublic static Set<Character> toSet(char[] array)
array
- a char arraypublic static Set<Short> toSet(short[] array)
array
- a short arraypublic static Set<Integer> toSet(int[] array)
array
- an int arraypublic static Set<Long> toSet(long[] array)
array
- a long arraypublic static Set<Float> toSet(float[] array)
array
- a float arraypublic static Set<Double> toSet(double[] array)
array
- a double arraypublic static <T> Set<T> toSet(Collection<T> self)
Example usage:
def result = [1, 2, 2, 2, 3].toSet() assert result instanceof Set assert result == [1, 2, 3] as Set
self
- a collectionpublic static <T> Set<T> toSet(Iterator<T> self)
self
- an iteratorpublic static <T> Set<T> toSet(Enumeration<T> self)
self
- an enumerationprotected static Object primitiveArrayGet(Object self, int idx)
self
- an array objectidx
- the index of interestprotected static List primitiveArrayGet(Object self, Range range)
self
- an array objectrange
- the range of indices of interestprotected static List primitiveArrayGet(Object self, Collection indices)
self
- an array objectindices
- the indices of interestprotected static Object primitiveArrayPut(Object self, int idx, Object newValue)
self
- an objectidx
- the index of interestnewValue
- the new value to be put into the index of interestpublic static Character toCharacter(String self)
self
- a Stringpublic static Boolean toBoolean(String self)
self
- a Stringpublic static Boolean toBoolean(Boolean self)
self
- a Booleanpublic static String[] split(String self)
self
- the string to splitpublic static CharSequence[] split(CharSequence self)
self
- the CharSequence to splitsplit(String)
public static String capitalize(String self)
assert 'h'.capitalize() == 'H' assert 'hello'.capitalize() == 'Hello' assert 'hello world'.capitalize() == 'Hello world' assert 'Hello World' == 'hello world'.split(' ').collect{ it.capitalize() }.join(' ')
self
- The string to capitalizepublic static CharSequence capitalize(CharSequence self)
self
- The CharSequence to capitalizecapitalize(String)
public static String expand(String self)
self
- A String to expandexpand(java.lang.String, int)
public static CharSequence expand(CharSequence self)
self
- A CharSequence to expandexpand(java.lang.String)
public static String expand(String self, int tabStop)
self
- A String to expandtabStop
- The number of spaces a tab representspublic static CharSequence expand(CharSequence self, int tabStop)
self
- A CharSequence to expandtabStop
- The number of spaces a tab representsexpand(String, int)
public static String expandLine(String self, int tabStop)
self
- A line to expandtabStop
- The number of spaces a tab representspublic static CharSequence expandLine(CharSequence self, int tabStop)
self
- A line to expandtabStop
- The number of spaces a tab representsexpandLine(String, int)
public static String unexpand(String self)
self
- A String to unexpandunexpand(java.lang.String, int)
public static CharSequence unexpand(CharSequence self)
self
- A CharSequence to unexpandunexpand(java.lang.String)
public static String unexpand(String self, int tabStop)
self
- A String to unexpandtabStop
- The number of spaces a tab representspublic static CharSequence unexpand(CharSequence self, int tabStop)
self
- A CharSequence to unexpandtabStop
- The number of spaces a tab representsunexpand(String, int)
public static String unexpandLine(String self, int tabStop)
self
- A line to unexpandtabStop
- The number of spaces a tab representspublic static CharSequence unexpandLine(CharSequence self, int tabStop)
self
- A line to unexpandtabStop
- The number of spaces a tab representsunexpandLine(String, int)
public static String[] split(GString self)
self
- the GString to splitsplit(java.lang.String)
public static List<String> tokenize(String self, String token)
self
- a Stringtoken
- the delimiterStringTokenizer.StringTokenizer(java.lang.String, java.lang.String)
public static List<CharSequence> tokenize(CharSequence self, CharSequence token)
self
- a CharSequencetoken
- the delimitertokenize(String, String)
public static List<String> tokenize(String self, Character token)
char pathSep = ':' assert "/tmp:/usr".tokenize(pathSep) == ["/tmp", "/usr"]
self
- a Stringtoken
- the delimiterStringTokenizer.StringTokenizer(java.lang.String, java.lang.String)
public static List<CharSequence> tokenize(CharSequence self, Character token)
self
- a CharSequencetoken
- the delimitertokenize(String, Character)
public static List<String> tokenize(String self)
self
- a StringStringTokenizer.StringTokenizer(java.lang.String)
public static List<CharSequence> tokenize(CharSequence self)
self
- a CharSequencetokenize(String)
public static String plus(String left, Object value)
left
- a Stringvalue
- any Objectpublic static CharSequence plus(CharSequence left, Object value)
left
- a CharSequencevalue
- any Objectpublic static String plus(Number value, String right)
value
- a Numberright
- a Stringpublic static String plus(StringBuffer left, String value)
left
- a StringBuffervalue
- a Stringpublic static String minus(String self, Object target)
self
- a Stringtarget
- an object representing the part to removepublic static CharSequence minus(CharSequence self, Object target)
self
- a CharSequencetarget
- an object representing the part to removeminus(String, Object)
public static boolean contains(String self, String text)
Collection.contains(java.lang.Object)
to make Strings more polymorphic.
This method is not required on JDK 1.5 onwardsself
- a Stringtext
- a String to look forpublic static boolean contains(CharSequence self, CharSequence text)
Collection.contains(java.lang.Object)
to make CharSequences more polymorphic.self
- a CharSequencetext
- the CharSequence to look forcontains(String, String)
public static int count(String self, String text)
self
- a Stringtext
- a substringpublic static int count(CharSequence self, CharSequence text)
self
- a CharSequencetext
- a sub CharSequencecount(String, String)
public static String next(String self)
self
- a Stringpublic static CharSequence next(CharSequence self)
self
- a CharSequencenext(String)
public static String previous(String self)
self
- a Stringpublic static CharSequence previous(CharSequence self)
self
- a CharSequenceprevious(String)
public static Process execute(String self) throws IOException
self
as a command-line process.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
self
- a command line StringIOException
- if an IOException occurs.public static Process execute(String self, String[] envp, File dir) throws IOException
self
with environment defined by envp
and under the working directory dir
.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
self
- a command line String to be executed.envp
- an array of Strings, each element of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static Process execute(String self, List envp, File dir) throws IOException
self
with environment defined
by envp
and under the working directory dir
.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
self
- a command line String to be executed.envp
- a List of Objects (converted to Strings using toString), each member of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static Process execute(String[] commandArray) throws IOException
String
array.
The first item in the array is the command; the others are the parameters.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commandArray
- an array of String containing the command name and
parameters as separate items in the array.
IOException
- if an IOException occurs.public static Process execute(String[] commandArray, String[] envp, File dir) throws IOException
String
array given in the first parameter,
with the environment defined by envp
and under the working directory dir
.
The first item in the array is the command; the others are the parameters.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commandArray
- an array of String containing the command name and
parameters as separate items in the array.
envp
- an array of Strings, each member of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static Process execute(String[] commandArray, List envp, File dir) throws IOException
String
array given in the first parameter,
with the environment defined by envp
and under the working directory dir
.
The first item in the array is the command; the others are the parameters.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commandArray
- an array of String containing the command name and
parameters as separate items in the array.
envp
- a List of Objects (converted to Strings using toString), each member of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static Process execute(List commands) throws IOException
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commands
- a list containing the command name and
parameters as separate items in the list.IOException
- if an IOException occurs.public static Process execute(List commands, String[] envp, File dir) throws IOException
envp
and under the working directory dir
.
The first item in the list is the command; the others are the parameters. The toString()
method is called on items in the list to convert them to Strings.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commands
- a List containing the command name and
parameters as separate items in the list.envp
- an array of Strings, each member of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static Process execute(List commands, List envp, File dir) throws IOException
envp
and under the working directory dir
.
The first item in the list is the command; the others are the parameters. The toString()
method is called on items in the list to convert them to Strings.
For more control over Process construction you can use
java.lang.ProcessBuilder
(JDK 1.5+).
commands
- a List containing the command name and
parameters as separate items in the list.envp
- a List of Objects (converted to Strings using toString), each member of which
has environment variable settings in the format
name=value, or
null if the subprocess should inherit
the environment of the current process.dir
- the working directory of the subprocess, or
null if the subprocess should inherit
the working directory of the current process.IOException
- if an IOException occurs.public static String multiply(String self, Number factor)
self
- a String to be repeatedfactor
- the number of times the String should be repeatedIllegalArgumentException
- if the number of repetitions is < 0public static CharSequence multiply(CharSequence self, Number factor)
self
- a CharSequence to be repeatedfactor
- the number of times the CharSequence should be repeatedIllegalArgumentException
- if the number of repetitions is < 0public static String toString(boolean[] self)
self
- an arraypublic static String toString(byte[] self)
self
- an arraypublic static String toString(char[] self)
self
- an arraypublic static String toString(short[] self)
self
- an arraypublic static String toString(int[] self)
self
- an arraypublic static String toString(long[] self)
self
- an arraypublic static String toString(float[] self)
self
- an arraypublic static String toString(double[] self)
self
- an arraypublic static String toString(AbstractMap self)
self
- a MaptoMapString(java.util.Map)
public static String toMapString(Map self)
[one:1, two:2, three:3]
.self
- a Mappublic static String toMapString(Map self, int maxSize)
[one:1, two:2, three:3]
.self
- a MapmaxSize
- stop after approximately this many characters and append '...'public static String toString(AbstractCollection self)
[1, 2, a]
.self
- a CollectiontoListString(java.util.Collection)
public static String toListString(Collection self)
[1, 2, a]
.self
- a Collectionpublic static String toListString(Collection self, int maxSize)
[1, 2, a]
.self
- a CollectionmaxSize
- stop after approximately this many characters and append '...'public static String toString(Object[] self)
self
- an Object[]toArrayString(java.lang.Object[])
public static String toArrayString(Object[] self)
{1, 2, "a"}
.self
- an Object[]public static String toString(Object value)
value
- an objectpublic static Character next(Character self)
self
- a Characterpublic static Number next(Number self)
self
- a Numberpublic static Character previous(Character self)
self
- a Characterpublic static Number previous(Number self)
self
- a Numberpublic static Number plus(Character left, Number right)
left
- a Characterright
- a NumberInteger.valueOf(int)
public static Number plus(Number left, Character right)
left
- a Numberright
- a CharacterInteger.valueOf(int)
public static Number plus(Character left, Character right)
left
- a Characterright
- a Characterplus(java.lang.Number, java.lang.Character)
public static int compareTo(Character left, Number right)
left
- a Characterright
- a Numberpublic static int compareTo(Number left, Character right)
left
- a Numberright
- a Characterpublic static int compareTo(Character left, Character right)
left
- a Characterright
- a Characterpublic static int compareTo(Number left, Number right)
left
- a Numberright
- another Number to compare topublic static Number minus(Character left, Number right)
left
- a Characterright
- a Numberpublic static Number minus(Number left, Character right)
left
- a Numberright
- a Characterpublic static Number minus(Character left, Character right)
left
- a Characterright
- a Characterpublic static Number multiply(Character left, Number right)
left
- a Characterright
- a Numberpublic static Number multiply(Number left, Character right)
left
- a Numberright
- a Characterpublic static Number multiply(Character left, Character right)
left
- a Characterright
- another Characterpublic static Number multiply(BigDecimal left, Double right)
left
- a BigDecimalright
- a Doublepublic static Number multiply(BigDecimal left, BigInteger right)
left
- a BigDecimalright
- a BigIntegerpublic static Number power(Number self, Number exponent)
self
- a Numberexponent
- a Number exponentpublic static Number power(BigDecimal self, Integer exponent)
self
- a BigDecimalexponent
- an Integer exponentpublic static Number power(BigInteger self, Integer exponent)
self
- a BigIntegerexponent
- an Integer exponentpublic static Number power(Integer self, Integer exponent)
self
- an Integerexponent
- an Integer exponentpublic static Number power(Long self, Integer exponent)
self
- a Longexponent
- an Integer exponentpublic static Number div(Character left, Number right)
left
- a Characterright
- a Numberpublic static Number div(Number left, Character right)
left
- a Numberright
- a Characterpublic static Number div(Character left, Character right)
left
- a Characterright
- another Characterpublic static Number intdiv(Character left, Number right)
left
- a Characterright
- a Numberpublic static Number intdiv(Number left, Character right)
left
- a Numberright
- a Characterpublic static Number intdiv(Character left, Character right)
left
- a Characterright
- another Characterpublic static Number intdiv(Number left, Number right)
left
- a Numberright
- another Numberpublic static Number or(Number left, Number right)
left
- a Numberright
- another Number to bitwise ORpublic static Number and(Number left, Number right)
left
- a Numberright
- another Number to bitwise ANDpublic static BitSet and(BitSet left, BitSet right)
left
- a BitSetright
- another BitSet to bitwise ANDpublic static BitSet xor(BitSet left, BitSet right)
left
- a BitSetright
- another BitSet to bitwise ANDpublic static BitSet bitwiseNegate(BitSet self)
self
- a BitSetpublic static BitSet or(BitSet left, BitSet right)
left
- a BitSetright
- another BitSet to bitwise ANDpublic static Number xor(Number left, Number right)
left
- a Numberright
- another Number to bitwse XORpublic static Number mod(Number left, Number right)
left
- a Numberright
- another Number to modpublic static Number unaryMinus(Number left)
-10
left
- a Numberpublic static void times(Number self, Closure closure)
10.times { println it }Prints the numbers 0 through 9.
self
- a Numberclosure
- the closure to call a number of timespublic static void upto(Number self, Number to, Closure closure)
self
- a Numberto
- another Number to go up toclosure
- the closure to callpublic static void upto(long self, Number to, Closure closure)
self
- a longto
- the end numberclosure
- the code to execute for each numberpublic static void upto(Long self, Number to, Closure closure)
self
- a Longto
- the end numberclosure
- the code to execute for each numberpublic static void upto(float self, Number to, Closure closure)
self
- a floatto
- the end numberclosure
- the code to execute for each numberpublic static void upto(Float self, Number to, Closure closure)
self
- a Floatto
- the end numberclosure
- the code to execute for each numberpublic static void upto(double self, Number to, Closure closure)
self
- a doubleto
- the end numberclosure
- the code to execute for each numberpublic static void upto(Double self, Number to, Closure closure)
self
- a Doubleto
- the end numberclosure
- the code to execute for each numberpublic static void upto(BigInteger self, Number to, Closure closure)
0.upto( 10 ) { println it }Prints numbers 0 to 10
self
- a BigIntegerto
- the end numberclosure
- the code to execute for each numberpublic static void upto(BigDecimal self, Number to, Closure closure)
0.1.upto( 10 ) { println it }Prints numbers 0.1, 1.1, 2.1... to 9.1
self
- a BigDecimalto
- the end numberclosure
- the code to execute for each numberpublic static void downto(Number self, Number to, Closure closure)
self
- a Numberto
- another Number to go down toclosure
- the closure to callpublic static void downto(long self, Number to, Closure closure)
self
- a longto
- the end numberclosure
- the code to execute for each numberpublic static void downto(Long self, Number to, Closure closure)
self
- a Longto
- the end numberclosure
- the code to execute for each numberpublic static void downto(float self, Number to, Closure closure)
self
- a floatto
- the end numberclosure
- the code to execute for each numberpublic static void downto(Float self, Number to, Closure closure)
self
- a Floatto
- the end numberclosure
- the code to execute for each numberpublic static void downto(double self, Number to, Closure closure)
self
- a doubleto
- the end numberclosure
- the code to execute for each numberpublic static void downto(Double self, Number to, Closure closure)
self
- a Doubleto
- the end numberclosure
- the code to execute for each numberpublic static void downto(BigInteger self, Number to, Closure closure)
self
- a BigIntegerto
- the end numberclosure
- the code to execute for each numberpublic static void downto(BigDecimal self, Number to, Closure closure)
10.5.downto(0) { println it }Prints numbers 10.5, 9.5 ... to 0.5.
self
- a BigDecimalto
- the end numberclosure
- the code to execute for each numberpublic static void step(Number self, Number to, Number stepNumber, Closure closure)
0.step( 10, 2 ) { println it }Prints even numbers 0 through 8.
self
- a Number to start withto
- a Number to go up to, exclusivestepNumber
- a Number representing the step incrementclosure
- the closure to callpublic static int abs(Number number)
number
- a Numberpublic static long abs(Long number)
number
- a Longpublic static float abs(Float number)
number
- a Floatpublic static double abs(Double number)
number
- a Doublepublic static int round(Float number)
number
- a Floatpublic static float round(Float number, int precision)
number
- a Floatprecision
- the number of decimal places to keeppublic static float trunc(Float number, int precision)
number
- a Floatprecision
- the number of decimal places to keeppublic static float trunc(Float number)
number
- a Doublepublic static long round(Double number)
number
- a Doublepublic static double round(Double number, int precision)
number
- a Doubleprecision
- the number of decimal places to keeppublic static double trunc(Double number)
number
- a Doublepublic static double trunc(Double number, int precision)
number
- a Doubleprecision
- the number of decimal places to keeppublic static Integer toInteger(String self)
self
- a Stringpublic static Long toLong(String self)
self
- a Stringpublic static Short toShort(String self)
self
- a Stringpublic static Float toFloat(String self)
self
- a Stringpublic static Double toDouble(String self)
self
- a Stringpublic static BigInteger toBigInteger(String self)
self
- a Stringpublic static BigDecimal toBigDecimal(String self)
self
- a Stringpublic static boolean isInteger(String self)
self
- a Stringpublic static boolean isLong(String self)
self
- a Stringpublic static boolean isFloat(String self)
self
- a Stringpublic static boolean isDouble(String self)
self
- a Stringpublic static boolean isBigInteger(String self)
self
- a Stringpublic static boolean isBigDecimal(String self)
self
- a Stringpublic static boolean isNumber(String self)
self
- a StringisBigDecimal(java.lang.String)
public static Integer toInteger(CharSequence self)
self
- a CharSequencetoInteger(java.lang.String)
public static Long toLong(CharSequence self)
self
- a CharSequencetoLong(java.lang.String)
public static Short toShort(CharSequence self)
self
- a CharSequencetoShort(java.lang.String)
public static Float toFloat(CharSequence self)
self
- a CharSequencetoFloat(java.lang.String)
public static Double toDouble(CharSequence self)
self
- a CharSequencetoDouble(java.lang.String)
public static BigInteger toBigInteger(CharSequence self)
self
- a CharSequencetoBigInteger(java.lang.String)
public static BigDecimal toBigDecimal(CharSequence self)
self
- a CharSequencetoBigDecimal(java.lang.String)
public static boolean isInteger(CharSequence self)
self
- a CharSequenceisInteger(java.lang.String)
public static boolean isLong(CharSequence self)
self
- a CharSequenceisLong(java.lang.String)
public static boolean isFloat(CharSequence self)
self
- a CharSequenceisFloat(java.lang.String)
public static boolean isDouble(CharSequence self)
self
- a CharSequenceisDouble(java.lang.String)
public static boolean isBigInteger(CharSequence self)
self
- a CharSequenceisBigInteger(java.lang.String)
public static boolean isBigDecimal(CharSequence self)
self
- a CharSequenceisBigDecimal(java.lang.String)
public static boolean isNumber(CharSequence self)
self
- a CharSequenceisNumber(java.lang.String)
public static boolean isUpperCase(Character self)
self
- a CharacterCharacter.isUpperCase(char)
public static boolean isLowerCase(Character self)
self
- a CharacterCharacter.isLowerCase(char)
public static boolean isLetter(Character self)
self
- a CharacterCharacter.isLetter(char)
public static boolean isDigit(Character self)
self
- a CharacterCharacter.isDigit(char)
public static boolean isLetterOrDigit(Character self)
self
- a CharacterCharacter.isLetterOrDigit(char)
public static boolean isWhitespace(Character self)
self
- a CharacterCharacter.isWhitespace(char)
public static char toUpperCase(Character self)
self
- a Character to convertCharacter.isUpperCase(char)
,
String.toUpperCase()
public static char toLowerCase(Character self)
self
- a Character to convertCharacter.isLowerCase(char)
,
String.toLowerCase()
public static Integer toInteger(Number self)
self
- a Numberpublic static Long toLong(Number self)
self
- a Numberpublic static Float toFloat(Number self)
self
- a Numberpublic static Double toDouble(Number self)
self
- a Numberpublic static BigDecimal toBigDecimal(Number self)
self
- a Numberpublic static <T> T asType(Number self, Class<T> c)
asType(java.lang.Object, java.lang.Class)
:
self
- this numberc
- the desired type of the transformed resultpublic static BigInteger toBigInteger(Number self)
self
- a Numberpublic static Boolean and(Boolean left, Boolean right)
left
- left operatorright
- right operatorpublic static Boolean or(Boolean left, Boolean right)
left
- left operatorright
- right operatorpublic static Boolean implies(Boolean left, Boolean right)
left
- left operatorright
- right operatorpublic static Boolean xor(Boolean left, Boolean right)
left
- left operatorright
- right operatorpublic static ObjectOutputStream newObjectOutputStream(File file) throws IOException
file
- a fileIOException
- if an IOException occurs.public static ObjectOutputStream newObjectOutputStream(OutputStream outputStream) throws IOException
outputStream
- an output streamIOException
- if an IOException occurs.public static <T> T withObjectOutputStream(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.OutputStream, groovy.lang.Closure)
public static <T> T withObjectOutputStream(OutputStream outputStream, Closure<T> closure) throws IOException
outputStream
- am output streamclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.OutputStream, groovy.lang.Closure)
public static ObjectInputStream newObjectInputStream(File file) throws IOException
file
- a fileIOException
- if an IOException occurs.public static ObjectInputStream newObjectInputStream(InputStream inputStream) throws IOException
inputStream
- an input streamIOException
- if an IOException occurs.public static ObjectInputStream newObjectInputStream(InputStream inputStream, ClassLoader classLoader) throws IOException
inputStream
- an input streamclassLoader
- the class loader to use when loading the classIOException
- if an IOException occurs.public static ObjectInputStream newObjectInputStream(File file, ClassLoader classLoader) throws IOException
file
- a fileclassLoader
- the class loader to use when loading the classIOException
- if an IOException occurs.public static void eachObject(File self, Closure closure) throws IOException, ClassNotFoundException
self
- a Fileclosure
- a closureIOException
- if an IOException occurs.ClassNotFoundException
- if the class is not found.eachObject(java.io.ObjectInputStream, groovy.lang.Closure)
public static void eachObject(ObjectInputStream ois, Closure closure) throws IOException, ClassNotFoundException
ois
- an ObjectInputStream, closed after the operationclosure
- a closureIOException
- if an IOException occurs.ClassNotFoundException
- if the class is not found.public static <T> T withObjectInputStream(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T withObjectInputStream(File file, ClassLoader classLoader, Closure<T> closure) throws IOException
file
- a FileclassLoader
- the class loader to use when loading the classclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T withObjectInputStream(InputStream inputStream, Closure<T> closure) throws IOException
inputStream
- an input streamclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T withObjectInputStream(InputStream inputStream, ClassLoader classLoader, Closure<T> closure) throws IOException
inputStream
- an input streamclassLoader
- the class loader to use when loading the classclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T eachLine(String self, Closure<T> closure) throws IOException
self
- a Stringclosure
- a closureIOException
- if an error occurseachLine(java.lang.String, int, groovy.lang.Closure)
public static <T> T eachLine(CharSequence self, Closure<T> closure) throws IOException
self
- a CharSequenceclosure
- a closureIOException
- if an error occurseachLine(java.lang.String, groovy.lang.Closure)
public static <T> T eachLine(String self, int firstLine, Closure<T> closure) throws IOException
self
- a StringfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an error occurspublic static <T> T eachLine(CharSequence self, int firstLine, Closure<T> closure) throws IOException
self
- a CharSequencefirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an error occurseachLine(java.lang.String, int, groovy.lang.Closure)
public static <T> T eachLine(File self, Closure<T> closure) throws IOException
self
- a Fileclosure
- a closure (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.io.File, int, groovy.lang.Closure)
public static <T> T eachLine(File self, String charset, Closure<T> closure) throws IOException
self
- a Filecharset
- opens the file with a specified charsetclosure
- a closure (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.io.File, java.lang.String, int, groovy.lang.Closure)
public static <T> T eachLine(File self, int firstLine, Closure<T> closure) throws IOException
self
- a FilefirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(File self, String charset, int firstLine, Closure<T> closure) throws IOException
self
- a Filecharset
- opens the file with a specified charsetfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(InputStream stream, String charset, Closure<T> closure) throws IOException
stream
- a streamcharset
- opens the stream with a specified charsetclosure
- a closure (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.io.InputStream, java.lang.String, int, groovy.lang.Closure)
public static <T> T eachLine(InputStream stream, String charset, int firstLine, Closure<T> closure) throws IOException
stream
- a streamcharset
- opens the stream with a specified charsetfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(InputStream stream, Closure<T> closure) throws IOException
stream
- a streamclosure
- a closure (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.io.InputStream, int, groovy.lang.Closure)
public static <T> T eachLine(InputStream stream, int firstLine, Closure<T> closure) throws IOException
stream
- a streamfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(URL url, Closure<T> closure) throws IOException
url
- a URL to open and readclosure
- a closure to apply on each line (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.net.URL, int, groovy.lang.Closure)
public static <T> T eachLine(URL url, int firstLine, Closure<T> closure) throws IOException
url
- a URL to open and readfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure to apply on each line (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.InputStream, int, groovy.lang.Closure)
public static <T> T eachLine(URL url, String charset, Closure<T> closure) throws IOException
url
- a URL to open and readcharset
- opens the stream with a specified charsetclosure
- a closure to apply on each line (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.net.URL, java.lang.String, int, groovy.lang.Closure)
public static <T> T eachLine(URL url, String charset, int firstLine, Closure<T> closure) throws IOException
url
- a URL to open and readcharset
- opens the stream with a specified charsetfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure to apply on each line (arg 1 is line, optional arg 2 is line number)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(Reader self, Closure<T> closure) throws IOException
self
- a Reader, closed after the method returnsclosure
- a closure (arg 1 is line, optional arg 2 is line number starting at line 1)IOException
- if an IOException occurs.eachLine(java.io.Reader, int, groovy.lang.Closure)
public static <T> T eachLine(Reader self, int firstLine, Closure<T> closure) throws IOException
self
- a Reader, closed after the method returnsfirstLine
- the line number value used for the first line (default is 1, set to 0 to start counting from 0)closure
- a closure which will be passed each line (or for 2 arg closures the line and line count)IOException
- if an IOException occurs.public static <T> T splitEachLine(File self, String regex, Closure<T> closure) throws IOException
self
- a Fileregex
- the delimiting regular expressionclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(File self, Pattern pattern, Closure<T> closure) throws IOException
self
- a Filepattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(File self, String regex, String charset, Closure<T> closure) throws IOException
self
- a Fileregex
- the delimiting regular expressioncharset
- opens the file with a specified charsetclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(File self, Pattern pattern, String charset, Closure<T> closure) throws IOException
self
- a Filepattern
- the regular expression Pattern for the delimitercharset
- opens the file with a specified charsetclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(URL self, String regex, Closure<T> closure) throws IOException
self
- a URL to open and readregex
- the delimiting regular expressionclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(URL self, Pattern pattern, Closure<T> closure) throws IOException
self
- a URL to open and readpattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(URL self, String regex, String charset, Closure<T> closure) throws IOException
self
- a URL to open and readregex
- the delimiting regular expressioncharset
- opens the file with a specified charsetclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(URL self, Pattern pattern, String charset, Closure<T> closure) throws IOException
self
- a URL to open and readpattern
- the regular expression Pattern for the delimitercharset
- opens the file with a specified charsetclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(Reader self, String regex, Closure<T> closure) throws IOException
def s = 'The 3 quick\nbrown 4 fox' def result = '' new StringReader(s).splitEachLine(/\d/){ parts -> result += "${parts[0]}_${parts[1]}|" } assert result == 'The _ quick|brown _ fox|'
self
- a Reader, closed after the method returnsregex
- the delimiting regular expressionclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidString.split(java.lang.String)
public static <T> T splitEachLine(Reader self, Pattern pattern, Closure<T> closure) throws IOException
def s = 'The 3 quick\nbrown 4 fox' def result = '' new StringReader(s).splitEachLine(~/\d/){ parts -> result += "${parts[0]}_${parts[1]}|" } assert result == 'The _ quick|brown _ fox|'
self
- a Reader, closed after the method returnspattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidString.split(java.lang.String)
public static <T> T splitEachLine(InputStream stream, String regex, String charset, Closure<T> closure) throws IOException
stream
- an InputStreamregex
- the delimiting regular expressioncharset
- opens the stream with a specified charsetclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(InputStream stream, Pattern pattern, String charset, Closure<T> closure) throws IOException
stream
- an InputStreampattern
- the regular expression Pattern for the delimitercharset
- opens the stream with a specified charsetclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(InputStream stream, String regex, Closure<T> closure) throws IOException
stream
- an InputStreamregex
- the delimiting regular expressionclosure
- a closureIOException
- if an IOException occurs.PatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
public static <T> T splitEachLine(InputStream stream, Pattern pattern, Closure<T> closure) throws IOException
stream
- an InputStreampattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an IOException occurs.splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
public static <T> T splitEachLine(String self, String regex, Closure<T> closure) throws IOException
self
- a Stringregex
- the delimiting regular expressionclosure
- a closureIOException
- if an error occursPatternSyntaxException
- if the regular expression's syntax is invalidString.split(java.lang.String)
public static <T> T splitEachLine(CharSequence self, CharSequence regex, Closure<T> closure) throws IOException
self
- a CharSequenceregex
- the delimiting regular expressionclosure
- a closureIOException
- if an error occursPatternSyntaxException
- if the regular expression's syntax is invalidsplitEachLine(String, String, Closure)
public static <T> T splitEachLine(String self, Pattern pattern, Closure<T> closure) throws IOException
self
- a Stringpattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an error occursPattern.split(java.lang.CharSequence)
public static <T> T splitEachLine(CharSequence self, Pattern pattern, Closure<T> closure) throws IOException
self
- a CharSequencepattern
- the regular expression Pattern for the delimiterclosure
- a closureIOException
- if an error occurssplitEachLine(String, Pattern, Closure)
public static String readLine(Reader self) throws IOException
self
- a ReaderIOException
- if an IOException occurs.public static String denormalize(String self)
self
- a String objectpublic static CharSequence denormalize(CharSequence self)
self
- a CharSequence objectdenormalize(String)
public static String normalize(String self)
self
- a String objectpublic static CharSequence normalize(CharSequence self)
self
- a CharSequence objectnormalize(String)
public static List<String> readLines(String self) throws IOException
self
- a String objectIOException
- if an error occurspublic static List<CharSequence> readLines(CharSequence self) throws IOException
self
- a CharSequence objectIOException
- if an error occurspublic static List<String> readLines(File file) throws IOException
file
- a FileIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(File file, String charset) throws IOException
file
- a Filecharset
- opens the file with a specified charsetIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(InputStream stream) throws IOException
stream
- a streamIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(InputStream stream, String charset) throws IOException
stream
- a streamcharset
- opens the stream with a specified charsetIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(URL self) throws IOException
self
- a URLIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(URL self, String charset) throws IOException
self
- a URLcharset
- opens the URL with a specified charsetIOException
- if an IOException occurs.readLines(java.io.Reader)
public static List<String> readLines(Reader reader) throws IOException
reader
- a ReaderIOException
- if an IOException occurs.public static String getText(File file, String charset) throws IOException
file
- the file whose content we want to readcharset
- the charset used to read the content of the fileIOException
- if an IOException occurs.public static String getText(File file) throws IOException
file
- the file whose content we want to readIOException
- if an IOException occurs.public static String getText(URL url) throws IOException
url
- URL to read content fromIOException
- if an IOException occurs.public static String getText(URL url, Map parameters) throws IOException
url
- URL to read content fromparameters
- connection parametersIOException
- if an IOException occurs.public static String getText(URL url, String charset) throws IOException
url
- URL to read content fromcharset
- opens the stream with a specified charsetIOException
- if an IOException occurs.URLConnection.getInputStream()
public static String getText(URL url, Map parameters, String charset) throws IOException
url
- URL to read content fromparameters
- connection parameterscharset
- opens the stream with a specified charsetIOException
- if an IOException occurs.URLConnection.getInputStream()
public static String getText(InputStream is) throws IOException
is
- an input streamIOException
- if an IOException occurs.public static String getText(InputStream is, String charset) throws IOException
is
- an input streamcharset
- opens the stream with a specified charsetIOException
- if an IOException occurs.public static String getText(Reader reader) throws IOException
reader
- a Reader whose content we want to readIOException
- if an IOException occurs.getText(java.io.BufferedReader)
public static String getText(BufferedReader reader) throws IOException
reader
- a BufferedReader whose content we want to readIOException
- if an IOException occurs.public static byte[] getBytes(File file) throws IOException
file
- the file whose content we want to readIOException
- if an IOException occurs.public static byte[] getBytes(URL url) throws IOException
url
- URL to read content fromIOException
- if an IOException occurs.public static byte[] getBytes(InputStream is) throws IOException
is
- an input streamIOException
- if an IOException occurs.public static void setBytes(File file, byte[] bytes) throws IOException
file
- the file to write tobytes
- the byte[] to write to the fileIOException
- if an IOException occurs.public static void setBytes(OutputStream os, byte[] bytes) throws IOException
os
- an output streambytes
- the byte[] to write to the output streamIOException
- if an IOException occurs.public static void writeLine(BufferedWriter writer, String line) throws IOException
writer
- a BufferedWriterline
- the line to writeIOException
- if an IOException occurs.public static void write(File file, String text) throws IOException
file
- a Filetext
- the text to write to the FileIOException
- if an IOException occurs.public static void setText(File file, String text) throws IOException
file
- a Filetext
- the text to write to the FileIOException
- if an IOException occurs.write(java.io.File, java.lang.String)
public static void setText(File file, String text, String charset) throws IOException
myFile.setText('some text', charset)or with some help from
ExpandoMetaClass
, you could do something like:
myFile.metaClass.setText = { String s -> delegate.setText(s, 'UTF-8') } myfile.text = 'some text'
file
- A Filecharset
- The charset used when writing to the filetext
- The text to write to the FileIOException
- if an IOException occurs.write(java.io.File, java.lang.String, java.lang.String)
public static File leftShift(File file, Object text) throws IOException
file
- a Filetext
- the text to write to the FileIOException
- if an IOException occurs.public static File leftShift(File file, byte[] bytes) throws IOException
file
- a Filebytes
- the byte array to append to the end of the FileIOException
- if an IOException occurs.public static File leftShift(File file, InputStream data) throws IOException
append(java.io.File, java.io.InputStream)
file
- a Filedata
- an InputStream of data to write to the fileIOException
- if an IOException occurs.public static void write(File file, String text, String charset) throws IOException
file
- a Filetext
- the text to write to the Filecharset
- the charset usedIOException
- if an IOException occurs.public static void append(File file, Object text) throws IOException
file
- a Filetext
- the text to append at the end of the FileIOException
- if an IOException occurs.public static void append(File file, byte[] bytes) throws IOException
file
- a Filebytes
- the byte array to append to the end of the FileIOException
- if an IOException occurs.public static void append(File self, InputStream stream) throws IOException
self
- a Filestream
- stream to read data from.IOException
- if an IOException occurs.public static void append(File file, Object text, String charset) throws IOException
file
- a Filetext
- the text to append at the end of the Filecharset
- the charset usedIOException
- if an IOException occurs.public static void eachFile(File self, FileType fileType, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a file objectfileType
- if normal files or directories or both should be processedclosure
- the closure to invokeFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directorypublic static void eachFile(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a File (that happens to be a folder/directory)closure
- a closure (first parameter is the 'child' file)FileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryFile.listFiles()
,
eachFile(java.io.File, groovy.io.FileType, groovy.lang.Closure)
public static void eachDir(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a File (that happens to be a folder/directory)closure
- a closure (first parameter is the subdirectory file)FileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryFile.listFiles()
,
eachFile(java.io.File, groovy.io.FileType, groovy.lang.Closure)
public static void eachFileRecurse(File self, FileType fileType, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a file objectfileType
- if normal files or directories or both should be processedclosure
- the closure to invoke on each fileFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directorypublic static void traverse(File self, Map<String,Object> options, Closure closure) throws FileNotFoundException, IllegalArgumentException
closure
for each descendant file in this directory tree.
Sub-directories are recursively traversed as found.
The traversal can be adapted by providing various options in the options
Map according
to the following keys:FileType
enum to determine if normal files or directories or both are processedClosure
run before each directory is processed and optionally returning a FileVisitResult
value
which can be used to control subsequent processing.Closure
run after each directory is processed and optionally returning a FileVisitResult
value
which can be used to control subsequent processing.FileType.FILES
)isCase(java.lang.Object, java.lang.Object)
method). If set,
only files/dirs which match are candidates for visiting.isCase(java.lang.Object, java.lang.Object)
method). If set,
only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)isCase(java.lang.Object, java.lang.Object)
method).
If set, any candidates which match won't be visited.isCase(java.lang.Object, java.lang.Object)
method).
If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)Closure
which if set causes the files and subdirectories for each directory to be processed in sorted order.
Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.def totalSize = 0 def count = 0 def sortByTypeThenName = { a, b -> a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name } rootDir.traverse( type : FILES, nameFilter : ~/.*\.groovy/, preDir : { if (it.name == '.svn') return SKIP_SUBTREE }, postDir : { println "Found $count files in $it.name totalling $totalSize bytes" totalSize = 0; count = 0 }, postRoot : true sort : sortByTypeThenName ) {it -> totalSize += it.size(); count++ }
self
- a Fileoptions
- a Map of options to alter the traversal behaviorclosure
- the Closure to invoke on each file/directory and optionally returning a FileVisitResult
value
which can be used to control subsequent processingFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directory or illegal filter combinations are suppliedsort(java.util.Collection, groovy.lang.Closure)
,
FileVisitResult
,
FileType
public static void traverse(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException
traverse(java.io.File, java.util.Map, groovy.lang.Closure)
when
no options to alter the traversal behavior are required.self
- a Fileclosure
- the Closure to invoke on each file/directory and optionally returning a FileVisitResult
value
which can be used to control subsequent processingFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directorytraverse(java.io.File, java.util.Map, groovy.lang.Closure)
public static void traverse(File self, Map<String,Object> options) throws FileNotFoundException, IllegalArgumentException
traverse(java.io.File, java.util.Map, groovy.lang.Closure)
allowing the 'visit' closure
to be included in the options Map rather than as a parameter.self
- a Fileoptions
- a Map of options to alter the traversal behaviorFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directory or illegal filter combinations are suppliedtraverse(java.io.File, java.util.Map, groovy.lang.Closure)
public static void eachFileRecurse(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a Fileclosure
- a closureFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryeachFileRecurse(java.io.File, groovy.io.FileType, groovy.lang.Closure)
public static void eachDirRecurse(File self, Closure closure) throws FileNotFoundException, IllegalArgumentException
self
- a directoryclosure
- a closureFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryeachFileRecurse(java.io.File, groovy.io.FileType, groovy.lang.Closure)
public static void eachFileMatch(File self, FileType fileType, Object nameFilter, Closure closure) throws FileNotFoundException, IllegalArgumentException
isCase(java.lang.Object, java.lang.Object)
method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Both regular files and subdirectories may be candidates for matching depending
on the value of fileType.
// collect names of files in baseDir matching supplied regex pattern import static groovy.io.FileType.* def names = [] baseDir.eachFileMatch FILES, ~/foo\d\.txt/, { names << it.name } assert names == ['foo1.txt', 'foo2.txt'] // remove all *.bak files in baseDir baseDir.eachFileMatch FILES, ~/.*\.bak/, { File bak -> bak.delete() } // print out files > 4K in size from baseDir baseDir.eachFileMatch FILES, { new File(baseDir, it).size() > 4096 }, { println "$it.name ${it.size()}" }
self
- a filefileType
- whether normal files or directories or both should be processednameFilter
- the filter to perform on the name of the file/directory (using the isCase(java.lang.Object, java.lang.Object)
method)closure
- the closure to invokeFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directorypublic static void eachFileMatch(File self, Object nameFilter, Closure closure) throws FileNotFoundException, IllegalArgumentException
isCase(java.lang.Object, java.lang.Object)
method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Both regular files and subdirectories are matched.self
- a filenameFilter
- the nameFilter to perform on the name of the file (using the isCase(java.lang.Object, java.lang.Object)
method)closure
- the closure to invokeFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryeachFileMatch(java.io.File, groovy.io.FileType, java.lang.Object, groovy.lang.Closure)
public static void eachDirMatch(File self, Object nameFilter, Closure closure) throws FileNotFoundException, IllegalArgumentException
isCase(java.lang.Object, java.lang.Object)
method to determine if a match occurs. This method can be used
with different kinds of filters like regular expressions, classes, ranges etc.
Only subdirectories are matched; regular files are ignored.self
- a filenameFilter
- the nameFilter to perform on the name of the directory (using the isCase(java.lang.Object, java.lang.Object)
method)closure
- the closure to invokeFileNotFoundException
- if the given directory does not existIllegalArgumentException
- if the provided File object does not represent a directoryeachFileMatch(java.io.File, groovy.io.FileType, java.lang.Object, groovy.lang.Closure)
public static boolean deleteDir(File self)
The method returns
self
- a Filepublic static boolean renameTo(File self, String newPathName)
File.renameTo(File)
self
- a FilenewPathName
- The new pathname for the named filetrue
if and only if the renaming succeeded;
false
otherwisepublic static TimerTask runAfter(Timer timer, int delay, Closure closure)
timer
- a timer objectdelay
- the delay in milliseconds before running the closure codeclosure
- the closure to invokepublic static BufferedReader newReader(File file) throws IOException
file
- a FileIOException
- if an IOException occurs.public static BufferedReader newReader(File file, String charset) throws FileNotFoundException, UnsupportedEncodingException
file
- a Filecharset
- the charset for this FileFileNotFoundException
- if the File was not foundUnsupportedEncodingException
- if the encoding specified is not supportedpublic static BufferedReader newReader(InputStream self)
self
- an input streampublic static BufferedReader newReader(InputStream self, String charset) throws UnsupportedEncodingException
self
- an input streamcharset
- the charset for this input streamUnsupportedEncodingException
- if the encoding specified is not supportedpublic static <T> T withReader(File file, Closure<T> closure) throws IOException
file
- a file objectclosure
- a closureIOException
- if an IOException occurs.public static <T> T withReader(File file, String charset, Closure<T> closure) throws IOException
file
- a file objectcharset
- the charset for this input streamclosure
- a closureIOException
- if an IOException occurs.public static BufferedOutputStream newOutputStream(File file) throws IOException
file
- a file objectIOException
- if an IOException occurs.public static DataOutputStream newDataOutputStream(File file) throws IOException
file
- a file objectIOException
- if an IOException occurs.public static Object withOutputStream(File file, Closure closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.OutputStream, groovy.lang.Closure)
public static Object withInputStream(File file, Closure closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T withInputStream(URL url, Closure<T> closure) throws IOException
url
- a URLclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static <T> T withDataOutputStream(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.OutputStream, groovy.lang.Closure)
public static <T> T withDataInputStream(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.withStream(java.io.InputStream, groovy.lang.Closure)
public static BufferedWriter newWriter(File file) throws IOException
file
- a FileIOException
- if an IOException occurs.public static BufferedWriter newWriter(File file, boolean append) throws IOException
file
- a Fileappend
- true if data should be appended to the fileIOException
- if an IOException occurs.public static BufferedWriter newWriter(File file, String charset, boolean append) throws IOException
file
- a Filecharset
- the name of the encoding used to write in this fileappend
- true if in append modeIOException
- if an IOException occurs.public static BufferedWriter newWriter(File file, String charset) throws IOException
file
- a Filecharset
- the name of the encoding used to write in this fileIOException
- if an IOException occurs.public static <T> T withWriter(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.public static <T> T withWriter(File file, String charset, Closure<T> closure) throws IOException
file
- a Filecharset
- the charset usedclosure
- a closureIOException
- if an IOException occurs.public static <T> T withWriterAppend(File file, String charset, Closure<T> closure) throws IOException
file
- a Filecharset
- the charset usedclosure
- a closureIOException
- if an IOException occurs.public static <T> T withWriterAppend(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- a closureIOException
- if an IOException occurs.public static PrintWriter newPrintWriter(File file) throws IOException
file
- a FileIOException
- if an IOException occurs.public static PrintWriter newPrintWriter(File file, String charset) throws IOException
file
- a Filecharset
- the charsetIOException
- if an IOException occurs.public static PrintWriter newPrintWriter(Writer writer)
writer
- a writerpublic static <T> T withPrintWriter(File file, Closure<T> closure) throws IOException
file
- a Fileclosure
- the closure to invoke with the PrintWriterIOException
- if an IOException occurs.public static <T> T withPrintWriter(File file, String charset, Closure<T> closure) throws IOException
file
- a Filecharset
- the charsetclosure
- the closure to invoke with the PrintWriterIOException
- if an IOException occurs.public static <T> T withPrintWriter(Writer writer, Closure<T> closure) throws IOException
writer
- a writerclosure
- the closure to invoke with the PrintWriterIOException
- if an IOException occurs.public static <T> T withWriter(Writer writer, Closure<T> closure) throws IOException
writer
- the writer which is used and then closedclosure
- the closure that the writer is passed intoIOException
- if an IOException occurs.public static <T> T withReader(Reader reader, Closure<T> closure) throws IOException
reader
- the reader which is used and then closedclosure
- the closure that the writer is passed intoIOException
- if an IOException occurs.public static <T> T withStream(InputStream stream, Closure<T> closure) throws IOException
stream
- the stream which is used and then closedclosure
- the closure that the stream is passed intoIOException
- if an IOException occurs.public static <T> T withReader(URL url, Closure<T> closure) throws IOException
url
- a URLclosure
- the closure to invoke with the readerIOException
- if an IOException occurs.public static <T> T withReader(URL url, String charset, Closure<T> closure) throws IOException
url
- a URLcharset
- the charset usedclosure
- the closure to invoke with the readerIOException
- if an IOException occurs.public static <T> T withReader(InputStream in, Closure<T> closure) throws IOException
in
- a streamclosure
- the closure to invoke with the InputStreamIOException
- if an IOException occurs.InputStreamReader
public static <T> T withReader(InputStream in, String charset, Closure<T> closure) throws IOException
in
- a streamcharset
- the charset used to decode the streamclosure
- the closure to invoke with the readerIOException
- if an IOException occurs.InputStreamReader
public static <T> T withWriter(OutputStream stream, Closure<T> closure) throws IOException
stream
- the stream which is used and then closedclosure
- the closure that the writer is passed intoIOException
- if an IOException occurs.withWriter(java.io.Writer, groovy.lang.Closure)
public static <T> T withWriter(OutputStream stream, String charset, Closure<T> closure) throws IOException
stream
- the stream which is used and then closedcharset
- the charset usedclosure
- the closure that the writer is passed intoIOException
- if an IOException occurs.withWriter(java.io.Writer, groovy.lang.Closure)
public static <T> T withStream(OutputStream os, Closure<T> closure) throws IOException
os
- the stream which is used and then closedclosure
- the closure that the stream is passed intoIOException
- if an IOException occurs.public static BufferedInputStream newInputStream(File file) throws FileNotFoundException
file
- a FileFileNotFoundException
- if the file is not found.public static BufferedInputStream newInputStream(URL url) throws MalformedURLException, IOException
url
- a URLMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static BufferedInputStream newInputStream(URL url, Map parameters) throws MalformedURLException, IOException
url
- a URLparameters
- connection parametersMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static BufferedReader newReader(URL url) throws MalformedURLException, IOException
url
- a URLMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static BufferedReader newReader(URL url, Map parameters) throws MalformedURLException, IOException
url
- a URLparameters
- connection parametersMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException
url
- a URLcharset
- opens the stream with a specified charsetMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static BufferedReader newReader(URL url, Map parameters, String charset) throws MalformedURLException, IOException
url
- a URLparameters
- connection parameterscharset
- opens the stream with a specified charsetMalformedURLException
- is thrown if the URL is not well formedIOException
- if an I/O error occurs while creating the input streampublic static DataInputStream newDataInputStream(File file) throws FileNotFoundException
file
- a FileFileNotFoundException
- if the file is not found.public static void eachByte(File self, Closure closure) throws IOException
self
- a Fileclosure
- a closureIOException
- if an IOException occurs.eachByte(java.io.InputStream, groovy.lang.Closure)
public static void eachByte(File self, int bufferLen, Closure closure) throws IOException
self
- a FilebufferLen
- the length of the buffer to use.closure
- a 2 parameter closure which is passed the byte[] and a number of bytes successfully read.IOException
- if an IOException occurs.eachByte(java.io.InputStream, int, groovy.lang.Closure)
public static void eachByte(Byte[] self, Closure closure)
self
- a Byte arrayclosure
- a closureeach(java.lang.Object, groovy.lang.Closure)
public static void eachByte(byte[] self, Closure closure)
self
- a byte arrayclosure
- a closureeach(java.lang.Object, groovy.lang.Closure)
public static void eachByte(InputStream is, Closure closure) throws IOException
is
- stream to iterate over, closed after the method callclosure
- closure to apply to each byteIOException
- if an IOException occurs.public static void eachByte(InputStream is, int bufferLen, Closure closure) throws IOException
is
- stream to iterate over, closed after the method call.bufferLen
- the length of the buffer to use.closure
- a 2 parameter closure which is passed the byte[] and a number of bytes successfully read.IOException
- if an IOException occurs.public static void eachByte(URL url, Closure closure) throws IOException
url
- url to iterate overclosure
- closure to apply to each byteIOException
- if an IOException occurs.eachByte(java.io.InputStream, groovy.lang.Closure)
public static void eachByte(URL url, int bufferLen, Closure closure) throws IOException
url
- url to iterate overbufferLen
- the length of the buffer to use.closure
- a 2 parameter closure which is passed the byte[] and a number of bytes successfully read.IOException
- if an IOException occurs.eachByte(java.io.InputStream, int, groovy.lang.Closure)
public static void transformChar(Reader self, Writer writer, Closure closure) throws IOException
self
- a Reader objectwriter
- a Writer to receive the transformed charactersclosure
- a closure that performs the required transformationIOException
- if an IOException occurs.public static void transformLine(Reader reader, Writer writer, Closure closure) throws IOException
reader
- Lines of text to be transformed. Reader is closed afterwards.writer
- Where transformed lines are written. Writer is closed afterwards.closure
- Single parameter closure that is called to transform each line of
text from the reader, before writing it to the writer.IOException
- if an IOException occurs.public static void filterLine(Reader reader, Writer writer, Closure closure) throws IOException
reader
- a reader, closed after the callwriter
- a writer, closed after the callclosure
- the closure which returns booleansIOException
- if an IOException occurs.public static Writable filterLine(File self, Closure closure) throws IOException
self
- a Fileclosure
- a closure which returns a boolean indicating to filter
the line or notIOException
- if self
is not readablefilterLine(java.io.Reader, groovy.lang.Closure)
public static Writable filterLine(File self, String charset, Closure closure) throws IOException
self
- a Filecharset
- opens the file with a specified charsetclosure
- a closure which returns a boolean indicating to filter
the line or notIOException
- if an IOException occursfilterLine(java.io.Reader, groovy.lang.Closure)
public static void filterLine(File self, Writer writer, Closure closure) throws IOException
self
- a Filewriter
- a writer destination to write filtered lines toclosure
- a closure which takes each line as a parameter and returns
true
if the line should be written to this writer.IOException
- if self
is not readablefilterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static void filterLine(File self, Writer writer, String charset, Closure closure) throws IOException
self
- a Filewriter
- a writer destination to write filtered lines tocharset
- opens the file with a specified charsetclosure
- a closure which takes each line as a parameter and returns
true
if the line should be written to this writer.IOException
- if an IO error occursfilterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static Writable filterLine(Reader reader, Closure closure)
true
if the line should be passed to the writer.reader
- this readerclosure
- a closure used for filteringpublic static Writable filterLine(InputStream self, Closure predicate)
true
if the line should be passed to the writer.self
- an input streampredicate
- a closure which returns boolean and takes a linefilterLine(java.io.Reader, groovy.lang.Closure)
public static Writable filterLine(InputStream self, String charset, Closure predicate) throws UnsupportedEncodingException
true
if the line should be passed to the writer.self
- an input streamcharset
- opens the stream with a specified charsetpredicate
- a closure which returns boolean and takes a lineUnsupportedEncodingException
- if the encoding specified is not supportedfilterLine(java.io.Reader, groovy.lang.Closure)
public static void filterLine(InputStream self, Writer writer, Closure predicate) throws IOException
true
if the line should be passed to the
writer.self
- the InputStreamwriter
- a writer to write output topredicate
- a closure which returns true if a line should be acceptedIOException
- if an IOException occurs.filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static void filterLine(InputStream self, Writer writer, String charset, Closure predicate) throws IOException
true
if the line should be passed to the
writer.self
- the InputStreamwriter
- a writer to write output tocharset
- opens the stream with a specified charsetpredicate
- a closure which returns true if a line should be acceptedIOException
- if an IOException occurs.filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static Writable filterLine(URL self, Closure predicate) throws IOException
true
if the line should be passed to the writer.self
- a URLpredicate
- a closure which returns boolean and takes a lineIOException
- if an IO exception occursfilterLine(java.io.Reader, groovy.lang.Closure)
public static Writable filterLine(URL self, String charset, Closure predicate) throws IOException
true
if the line should be passed to the writer.self
- the URLcharset
- opens the URL with a specified charsetpredicate
- a closure which returns boolean and takes a lineIOException
- if an IO exception occursfilterLine(java.io.Reader, groovy.lang.Closure)
public static void filterLine(URL self, Writer writer, Closure predicate) throws IOException
true
if the line should be passed to the
writer.self
- the URLwriter
- a writer to write output topredicate
- a closure which returns true if a line should be acceptedIOException
- if an IOException occurs.filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static void filterLine(URL self, Writer writer, String charset, Closure predicate) throws IOException
true
if the line should be passed to the
writer.self
- the URLwriter
- a writer to write output tocharset
- opens the URL with a specified charsetpredicate
- a closure which returns true if a line should be acceptedIOException
- if an IOException occurs.filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
public static byte[] readBytes(File file) throws IOException
file
- a FileIOException
- if an IOException occurs.public static <T> T withStreams(Socket socket, Closure<T> closure) throws IOException
socket
- a Socketclosure
- a ClosureIOException
- if an IOException occurs.public static <T> T withObjectStreams(Socket socket, Closure<T> closure) throws IOException
socket
- this Socketclosure
- a ClosureIOException
- if an IOException occurs.public static Writer leftShift(Socket self, Object value) throws IOException
self
- a Socketvalue
- a value to appendIOException
- if an IOException occurs.public static OutputStream leftShift(Socket self, byte[] value) throws IOException
self
- a Socketvalue
- a value to appendIOException
- if an IOException occurs.public static Socket accept(ServerSocket serverSocket, Closure closure) throws IOException
serverSocket
- a ServerSocketclosure
- a ClosureIOException
- if an IOException occurs.ServerSocket.accept()
public static Socket accept(ServerSocket serverSocket, boolean runInANewThread, Closure closure) throws IOException
serverSocket
- a ServerSocketrunInANewThread
- This flag should be true, if the closure should be invoked in a new thread, else false.closure
- a ClosureIOException
- if an IOException occurs.ServerSocket.accept()
public static File asWritable(File file)
Writable
.file
- a Filepublic static <T> T asType(File f, Class<T> c)
Writable
or delegates to default
asType(java.lang.Object, java.lang.Class)
.f
- a Filec
- the desired classpublic static File asWritable(File file, String encoding)
file
- a Fileencoding
- the encoding to be used when reading the file's contentspublic static List<String> toList(String self)
self
- a Stringpublic static List<CharSequence> toList(CharSequence self)
self
- a CharSequencetoSet(String)
public static Set<String> toSet(String self)
Example usage:
assert 'groovy'.toSet() == ['v', 'g', 'r', 'o', 'y'] as Set assert "abc".toSet().iterator()[0] instanceof String
self
- a Stringpublic static Set<CharSequence> toSet(CharSequence self)
self
- a CharSequencetoSet(String)
public static char[] getChars(String self)
self
- a StringString.toCharArray()
public static char[] getChars(CharSequence self)
self
- a CharSequencegetChars(String)
public static <T> T asType(GString self, Class<T> c)
asType(java.lang.Object, java.lang.Class)
self
- a GStringc
- the desired classpublic static <T> T asType(String self, Class<T> c)
Provides a method to perform custom 'dynamic' type conversion
to the given class using the as
operator.
'123' as Double
By default, the following types are supported:
asType(java.lang.Object, java.lang.Class)
.self
- a Stringc
- the desired classpublic static <T> T asType(CharSequence self, Class<T> c)
Provides a method to perform custom 'dynamic' type conversion
to the given class using the as
operator.
self
- a CharSequencec
- the desired classasType(String, Class)
public static String eachMatch(String self, String regex, Closure closure)
self
- the source stringregex
- a Regex stringclosure
- a closure with one parameter or as much parameters as groupspublic static String eachMatch(CharSequence self, CharSequence regex, Closure closure)
self
- the source CharSequenceregex
- a Regex CharSequenceclosure
- a closure with one parameter or as much parameters as groupseachMatch(String, String, groovy.lang.Closure)
public static String eachMatch(String self, Pattern pattern, Closure closure)
self
- the source stringpattern
- a regex Patternclosure
- a closure with one parameter or as much parameters as groupspublic static String eachMatch(CharSequence self, Pattern pattern, Closure closure)
self
- the source CharSequencepattern
- a regex Patternclosure
- a closure with one parameter or as much parameters as groupseachMatch(String, Pattern, groovy.lang.Closure)
public static int findIndexOf(Object self, Closure closure)
self
- the iteration object over which to iterateclosure
- the filter to perform a match on the collectionpublic static int findIndexOf(Object self, int startIndex, Closure closure)
self
- the iteration object over which to iteratestartIndex
- start matching from this indexclosure
- the filter to perform a match on the collectionpublic static int findLastIndexOf(Object self, Closure closure)
self
- the iteration object over which to iterateclosure
- the filter to perform a match on the collectionpublic static int findLastIndexOf(Object self, int startIndex, Closure closure)
self
- the iteration object over which to iteratestartIndex
- start matching from this indexclosure
- the filter to perform a match on the collectionpublic static List<Number> findIndexValues(Object self, Closure closure)
self
- the iteration object over which to iterateclosure
- the filter to perform a match on the collectionpublic static List<Number> findIndexValues(Object self, Number startIndex, Closure closure)
self
- the iteration object over which to iteratestartIndex
- start matching from this indexclosure
- the filter to perform a match on the collectionpublic static ClassLoader getRootLoader(ClassLoader self)
null
will be returned. The name is used for comparison because
a direct comparison using == may fail as the class may be loaded through
different classloaders.self
- a ClassLoaderRootLoader
public static <T> T asType(Object obj, Class<T> type)
obj
- the object to converttype
- the goal typepublic static <T> T newInstance(Class<T> c)
c
- a classpublic static <T> T newInstance(Class<T> c, Object[] args)
newInstance(null)
or simply
newInstance()
for the default (no-arg) constructor.c
- a classargs
- the constructor argumentspublic static MetaClass getMetaClass(Class c)
String.metaClass.myMethod = { println "foo" }
c
- The java.lang.Class instancepublic static MetaClass getMetaClass(Object obj)
obj
- The object in questionpublic static MetaClass getMetaClass(GroovyObject obj)
obj
- The object in questionpublic static void setMetaClass(Class self, MetaClass metaClass)
self
- the class whose metaclass we wish to setmetaClass
- the new MetaClasspublic static void setMetaClass(Object self, MetaClass metaClass)
self
- the object whose metaclass we want to setmetaClass
- the new metaclass valuepublic static MetaClass metaClass(Class self, Closure closure)
self
- the class whose metaclass we wish to updateclosure
- the closure representing the new metaclassGroovyRuntimeException
- if the metaclass can't be set for this classpublic static MetaClass metaClass(Object self, Closure closure)
self
- the object whose metaclass we wish to updateclosure
- the closure representing the new metaclassGroovyRuntimeException
- if the metaclass can't be set for this objectpublic static <T> Iterator<T> iterator(T[] a)
a
- an arrayDefaultTypeTransformation.asCollection(java.lang.Object[])
public static Iterator iterator(Object o)
o
- an objectDefaultTypeTransformation.asCollection(java.lang.Object)
public static <T> Iterator<T> iterator(Enumeration<T> enumeration)
remove()
method is unsupported since the
underlying Enumeration does not provide a mechanism for removing items.enumeration
- an Enumeration objectpublic static Iterator iterator(Matcher matcher)
Iterator
which traverses each match.matcher
- a Matcher objectMatcher.group()
public static Iterator<String> iterator(Reader self)
self
- a Reader objectBufferedReader.readLine()
public static Iterator<Byte> iterator(InputStream self)
self
- an InputStream objectpublic static Iterator<Byte> iterator(DataInputStream self)
self
- a DataInputStream objectpublic static <T> Iterator<T> iterator(Iterator<T> self)
self
- an iterator objectpublic static List<MetaMethod> respondsTo(Object self, String name, Object[] argTypes)
Returns an object satisfying Groovy truth if the implementing MetaClass responds to a method with the given name and arguments types.
Note that this method's return value is based on realised methods and does not take into account objects or classes that implement invokeMethod or methodMissing
This method is "safe" in that it will always return a value and never throw an exception
self
- The object to inspectname
- The name of the method of interestargTypes
- The argument types to match againstMetaObjectProtocol.respondsTo(java.lang.Object, java.lang.String, java.lang.Object[])
public static List<MetaMethod> respondsTo(Object self, String name)
Returns an object satisfying Groovy truth if the implementing MetaClass responds to a method with the given name regardless of the arguments.
Note that this method's return value is based on realised methods and does not take into account objects or classes that implement invokeMethod or methodMissing
This method is "safe" in that it will always return a value and never throw an exception
self
- The object to inspectname
- The name of the method of interestMetaObjectProtocol.respondsTo(java.lang.Object, java.lang.String)
public static MetaProperty hasProperty(Object self, String name)
Returns true of the implementing MetaClass has a property of the given name
Note that this method will only return true for realised properties and does not take into account implementation of getProperty or propertyMissing
self
- The object to inspectname
- The name of the property of interestMetaObjectProtocol.hasProperty(java.lang.Object, java.lang.String)