Class Util
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Exception used to interrupt a tree walk of any kind.static class
Visitor which looks for an OVER clause inside a tree ofSqlNode
objects. -
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic <X> UnaryOperator<X>
andThen
(UnaryOperator<X> op1, UnaryOperator<X> op2) Returns an operator that appliesop1
and thenop2
.static <K,
V> Map<K, V> asIndexMap
(Collection<V> values, com.google.common.base.Function<V, K> function) Deprecated.static <K,
V> Map<K, V> asIndexMapJ
(Collection<V> values, Function<V, K> function) Returns a map that is a view onto a collection of values, using the provided function to convert a value to a key.static void
asStringBuilder
(Appendable appendable, Consumer<StringBuilder> consumer) Given anAppendable
, performs an action that requires aStringBuilder
.static <K,
V> Map<K, V> Returns a map which ignores any write operation.static Calendar
calendar()
Creates aCalendar
in the UTC time zone and root locale.static Calendar
calendar
(long millis) Creates aCalendar
in the UTC time zone and root locale with a given time.static Calendar
Creates aCalendar
in the specified time zone.static <E> Iterable<E>
Converts anIterable
whose members are automatically down-cast to a given type.Converts a iterator whose members are automatically down-cast to a given type.static <E> List<E>
Converts a list whose members are automatically down-cast to a given type.static Throwable
causeOrSelf
(Throwable throwable) Returns cause of the given throwable if it is non-null or the throwable itself.static <E> com.google.common.collect.ImmutableList.Builder<E>
combine
(com.google.common.collect.ImmutableList.Builder<E> b0, com.google.common.collect.ImmutableList.Builder<E> b1) Combines a second immutable list builder into a first.static <E> ArrayList<E>
Combines a second array list into a first.static <T> String
Converts a list of a string, with commas between elements.static boolean
Returns whether an array of strings contains a given string among the firstlength
entries.static void
debugCode
(PrintStream out, String code) Prints the given code with line numbering.static <T> T
deprecated
(T argument, boolean fail) Deprecated.If a piece of code calls this method, it indicates that the code needs to be cleaned up.static void
discard
(boolean unused) Does nothing with its argument.static void
discard
(double unused) Does nothing with its argument.static void
discard
(int unused) Does nothing with its argument.static void
Does nothing with its argument.static <E> List<E>
distinctList
(Iterable<E> keys) Converts an iterable into a list with unique elements.static <E> List<E>
distinctList
(List<E> list) Converts a list into a list with unique elements.enumConstants
(Class<T> clazz) Creates a map of the values of an enumeration by name.static <T extends Enum<T>>
@Nullable TReturns the value of an enumeration with a particular name.static <T extends Enum<T>>
TReturns the value of an enumeration with a particular or default value if not found.static <T> boolean
equalShallow
(List<? extends T> list0, List<? extends T> list1) Returns whether two lists are equal to each other using shallow comparisons.static <E> Iterable<E>
Makes a collection of untyped elements appear as a list of strictly typed elements, by filtering out those which are not of the correct type.static <E> Iterable<E>
Filters an iterable.static <E> Collection<E>
filter
(Collection<?> collection, Class<E> includeFilter) static <E> Iterator<E>
Filters an iterator.static <E> List<E>
Returns a subset of a list containing only elements of a given type.static int
Looks for a string within a list of strings, using a given case-sensitivity policy, and returns the position at which the first match is found, or -1 if there are no matches.static <T> @PolyNull T
first
(@Nullable T v0, @PolyNull T v1) Returns the first value if it is not null, otherwise the second value.static boolean
Unboxes aBoolean
value, using a given default value if it is null.static byte
Unboxes aByte
value, using a given default value if it is null.static char
Unboxes aCharacter
value, using a given default value if it is null.static double
Unboxes aDouble
value, using a given default value if it is null.static float
Unboxes aFloat
value, using a given default value if it is null.static int
Unboxes aInteger
value, using a given default value if it is null.static long
Unboxes aLong
value, using a given default value if it is null.static short
Unboxes aShort
value, using a given default value if it is null.<E> E
Returns the first element of a list.static <E> List<E>
Returns the firstn
elements of a list.static <E> int
firstDuplicate
(List<E> list) Returns the ordinal of the first element in the list which is equal to a previous element in the list.static Charset
Returns theCharset
object representing the value ofCalciteSystemProperty.DEFAULT_CHARSET
.static String
Deprecated.static String
Deprecated.static String
Deprecated.UseThrowables.getStackTraceAsString(Throwable)
static int
hash
(int i, int j) Deprecated.static int
Deprecated.static int
Deprecated.static int
hashCode
(double v) Deprecated.static String
human
(double d) Converts a number into human-readable form, with 3 digits and a "K", "M" or "G" multiplier for thousands, millions or billions.immutableCopy
(Iterable<? extends Iterable<E>> lists) Returns a copy of a list of lists, making the component lists immutable if they are not already.static <E> boolean
intersects
(Collection<E> c0, Collection<E> c1) Returns whether two collections have any elements in common.static <E> boolean
isDefinitelyDistinctAndNonNull
(List<? extends @Nullable E> list) Returns whether the elements oflist
are definitely distinct and not null, working quickly and sometimes giving false negatives for large lists.static <E> boolean
isDistinct
(List<E> list) Returns whether the elements oflist
are distinct.static boolean
isNullOrEmpty
(@Nullable String s) Returns whether s == null or if s.length() == 0.static boolean
isSingleValue
(SqlCall call) Does nothing with its argument.static boolean
Returns true when input string is a valid Java identifier.static <E> E
Returns the last element of a list.static <E> List<E>
Returns the lastn
elements of a list.static String
Converts a list of strings to a string separated by newlines.static String
listToString
(List<String> list) Converts ["ab", "c"] to "ab"."c".static <K,
V> Map<K, V> Returns a hashmap with given contents.static boolean
Returns whether a name matches another according to a given case-sensitivity policy.static <T> Set<T>
Returns a set of the elements which are inset1
but not inset2
, without modifying either.static <E> List<E>
moveToHead
(List<? extends E> terms, Predicate<? super E> predicate) Returns a list with any elements for which the predicate is true moved to the head of the list.static RuntimeException
needToImplement
(@Nullable Object o) Returns aRuntimeException
indicating that a particular feature has not been implemented, but should be.static Error
Deprecated.Throw newAssertionError
static Error
Deprecated.Throw newAssertionError
static Error
Deprecated.Throw newRuntimeException
if checked; throw raw exception if unchecked orError
static Error
newInternal
(Throwable e, String s) Deprecated.Throw newAssertionError
if applicable; orRuntimeException
if e is checked; or raw exception if e is unchecked orError
.static double
nLogM
(double n, double m) static double
nLogN
(double d) static <T> Iterable<T>
Given a list with N elements [e0, e1, ..., eN-1] (where N is even), returns a list of the N / 2 elements [ (e0, e1), (e2, e3), ...static Locale
parseLocale
(String localeString) Parses a locale string.static void
permAssert
(boolean b, String description) Deprecated.UsePreconditions.checkArgument(boolean)
static void
Deprecated.UsePreconditions.checkArgument(boolean)
orObjects.requireNonNull(Object)
static void
Deprecated.UsePreconditions.checkArgument(boolean)
orObjects.requireNonNull(Object)
static void
print
(PrintWriter pw, @Nullable Object o, int indent) static void
print
(PrintWriter pw, Object o) Prints an object using reflection.static <E> StringBuilder
printIterable
(StringBuilder sb, Iterable<E> iterable) Prints a collection of elements to a StringBuilder, in the same format asAbstractCollection.toString()
.static void
printJavaString
(Appendable appendable, @Nullable String s, boolean nullMeansNull) Prints a string, enclosing in double quotes (") and escaping if necessary.static StringBuilder
printList
(StringBuilder sb, int elementCount, ObjIntConsumer<StringBuilder> consumer) Prints a set of elements to a StringBuilder, in the same format same asAbstractCollection.toString()
.static void
println
(PrintWriter pw, Object o) static PrintWriter
printWriter
(File file) Creates aPrintWriter
to a given file using UTF-8 character set.static PrintWriter
printWriter
(OutputStream out) Creates aPrintWriter
to a given output stream using UTF-8 character set.static <E> List<E>
quotientList
(List<E> list, int n, int k) Creates a list that returns everyn
th element of a list, starting at elementk
.range
(int end) range
(int start, int end) static String
readAllAsString
(Reader reader) Deprecated.static BufferedReader
Creates aBufferedReader
to read a given file using UTF-8 character set.static BufferedReader
reader
(InputStream in) Creates aBufferedReader
to a given input stream using UTF-8 character set.static String
Replaces every occurrence offind
ins
withreplace
.static String
Deprecated.UseSpaces.padRight(String, int)
static String
Deprecated.static <E> List<E>
Returns a view of a list, picking the elements of a list with the given set of ordinals.static <T> String
Converts a list of a string, with a given separator between elements.static <E> List<E>
Returns all but the first element of a list.static <E> List<E>
Returns all but the firstn
elements of a list.static <E> List<E>
Returns every element of a list but its last element.static <E> List<E>
Returns every element of a list but its lastn
elements.static void
squelchConnection
(@Nullable Connection connection) Deprecated.static void
squelchJar
(@Nullable JarFile jar) Deprecated.static void
squelchReader
(@Nullable Reader reader) Deprecated.static void
squelchStmt
(@Nullable Statement stmt) Deprecated.static void
squelchStream
(@Nullable InputStream stream) Deprecated.static void
squelchStream
(@Nullable OutputStream stream) Deprecated.static void
squelchWriter
(@Nullable Writer writer) Deprecated.static <E> boolean
startsWith
(List<E> list0, List<E> list1) Returns whether one list is a prefix of another.static String
stripDoubleQuotes
(String value) Converts double-quoted Java strings to their contents.static void
Records that an exception has been caught but will not be re-thrown.static RuntimeException
throwAsRuntime
(String message, Throwable throwable) This method rethrows input throwable as is (if its unchecked) with an extra message or wraps it withRuntimeException
and throws.static RuntimeException
throwAsRuntime
(Throwable throwable) This method rethrows input throwable as is (if its unchecked) or wraps it withRuntimeException
and throws.static void
throwIfUnchecked
(Throwable throwable) Deprecated.static <T> Collector<T,
?, com.google.common.collect.ImmutableList<T>> Deprecated.UseImmutableList.toImmutableList()
static String
Converts an arbitrary string into a string suitable for use as a Java identifier.Converts a string into tokens.static String
static <T> List<T>
Deprecated.toMap
(Properties properties) Converts aProperties
object to a
.Map
<String, String>static String
Converts a Java timezone to POSIX format, so that the boost C++ library can instantiate timezone objects.static String
Formats a double value to a String ensuring that the output is in scientific notation if the value is not "special".static String
Formats aBigDecimal
value to a string in scientific notation For example
A value of 0.00001234 would be formated as1.234E-5
A value of 100000.00 would be formated as1.00E5
A value of 100 (scale zero) would be formated as1E2
static <T> String
Converts an iterable to a string.static RuntimeException
Wraps an exception withRuntimeException
and return it.static URL
Deprecated.static <F,
T> Iterable<T> Transforms an iterable, applying a function to each element.static <F,
T> Iterator<T> Transforms an iterator.static <F,
T> List<T> Transforms a list, applying a function to each element.static <F,
T> List<T> transformIndexed
(List<? extends F> list, BiFunction<? super F, Integer, ? extends T> function) Transforms a list, applying a function to each element, also passing in the element's index in the list.unexpected
(E value) Returns an exception indicating that we didn't expect to find this enumeration here.
-
Field Details
-
LINE_SEPARATOR
System-dependent newline character.In general, you should not use this in expected results of tests. Expected results should be the expected result on Linux (or Mac OS) using '\n'. Apply
toLinux(String)
to Windows actual results, if necessary, to make them look like Linux actual. -
FILE_SEPARATOR
System-dependent file separator, for example, "/" or "\." -
FILE_TIMESTAMP_FORMAT
Datetime format string for generating a timestamp string to be used as part of a filename. Conforms to SimpleDateFormat conventions.- See Also:
-
-
Method Details
-
isSingleValue
Does nothing with its argument. Returns whether it is ensured that the call produces a single value- Parameters:
call
- the expression to evaluate- Returns:
- Whether it is ensured that the call produces a single value
-
discard
Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it. -
discard
public static void discard(int unused) Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it. -
discard
public static void discard(boolean unused) Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it. -
discard
public static void discard(double unused) Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it. -
swallow
Records that an exception has been caught but will not be re-thrown. If the tracer is not null, logs the exception to the tracer.- Parameters:
e
- Exceptionlogger
- If not null, logs exception to this logger
-
equalShallow
Returns whether two lists are equal to each other using shallow comparisons.- Parameters:
list0
- First listlist1
- Second list- Returns:
- Whether lists are same length and all of their elements are
equal using
==
(may be null).
-
hash
Deprecated.Combines two integers into a hash code. -
hash
Deprecated.Computes a hash code from an existing hash code and an object (which may be null). -
hashArray
Deprecated.Computes a hash code from an existing hash code and an array of objects (which may be null). -
hashCode
Deprecated.Computes the hash code of adouble
value. Equivalent toDouble
.hashCode(double)
, but that method was only introduced in JDK 1.8.- Parameters:
v
- Value- Returns:
- Hash code
-
minus
Returns a set of the elements which are inset1
but not inset2
, without modifying either. -
nLogN
public static double nLogN(double d) -
nLogM
public static double nLogM(double n, double m) -
print
Prints an object using reflection. We can handlenull
; arrays of objects and primitive values; for regular objects, we print all public fields. -
print
-
printJavaString
public static void printJavaString(Appendable appendable, @Nullable String s, boolean nullMeansNull) Prints a string, enclosing in double quotes (") and escaping if necessary. For example,printDoubleQuoted(w,"x\"y",false)
prints"x\"y"
.The appendable where the value is printed must not incur I/O operations. This method is not meant to be used for writing the values to permanent storage.
- Throws:
IllegalStateException
- if the print to the specified appendable fails due to I/O
-
println
-
toScientificNotation
Formats a double value to a String ensuring that the output is in scientific notation if the value is not "special". (Special values include infinities and NaN.) -
toScientificNotation
Formats aBigDecimal
value to a string in scientific notation For example
- A value of 0.00001234 would be formated as
1.234E-5
- A value of 100000.00 would be formated as
1.00E5
- A value of 100 (scale zero) would be formated as
1E2
If
bd
has a precision higher than 20, this method will truncate the output string to have a precision of 20 (no rounding will be done, just a truncate). - A value of 0.00001234 would be formated as
-
replace
Replaces every occurrence offind
ins
withreplace
. -
toURL
Deprecated.Creates a file-protocol URL for the given file.- Throws:
MalformedURLException
-
getFileTimestamp
Deprecated.Gets a timestamp string for use in file names. The generated timestamp string reflects the current time. -
stripDoubleQuotes
Converts double-quoted Java strings to their contents. For example,"foo\"bar"
becomesfoo"bar
. -
toJavaId
Converts an arbitrary string into a string suitable for use as a Java identifier.The mapping is one-to-one (that is, distinct strings will produce distinct java identifiers). The mapping is also reversible, but the inverse mapping is not implemented.
A valid Java identifier must start with a Unicode letter, underscore, or dollar sign ($). The other characters, if any, can be a Unicode letter, underscore, dollar sign, or digit.
This method uses an algorithm similar to URL encoding. Valid characters are unchanged; invalid characters are converted to an underscore followed by the hex code of the character; and underscores are doubled.
Examples:
toJavaId("foo")
returns"foo"
toJavaId("foo bar")
returns"foo_20_bar"
toJavaId("foo_bar")
returns"foo__bar"
toJavaId("0bar")
returns"_40_bar"
(digits are illegal as a prefix)toJavaId("foo0bar")
returns"foo0bar"
-
isValidJavaIdentifier
Returns true when input string is a valid Java identifier.- Parameters:
s
- input string- Returns:
- true when input string is a valid Java identifier
-
toLinux
-
toList
Deprecated.- Parameters:
iter
- iterator to materialize- Returns:
- materialized list
-
isNullOrEmpty
Returns whether s == null or if s.length() == 0. -
commaList
Converts a list of a string, with commas between elements.For example,
commaList(Arrays.asList({"a", "b"}))
returns "a, b".- Parameters:
list
- List- Returns:
- String representation of string
-
sepList
Converts a list of a string, with a given separator between elements. -
printIterable
Prints a collection of elements to a StringBuilder, in the same format asAbstractCollection.toString()
. -
printList
public static StringBuilder printList(StringBuilder sb, int elementCount, ObjIntConsumer<StringBuilder> consumer) Prints a set of elements to a StringBuilder, in the same format same asAbstractCollection.toString()
.The 'set' is represented by the number of elements and an action to perform for each element.
This method can be a very efficient way to convert a structure to a string, because the components can write directly to the StringBuilder rather than constructing intermediate strings.
-
getDefaultCharset
Returns theCharset
object representing the value ofCalciteSystemProperty.DEFAULT_CHARSET
.- Throws:
IllegalCharsetNameException
- If the given charset name is illegalUnsupportedCharsetException
- If no support for the named charset is available in this instance of the Java virtual machine
-
newInternal
Deprecated.Throw newAssertionError
-
newInternal
Deprecated.Throw newAssertionError
-
newInternal
Deprecated.Throw newRuntimeException
if checked; throw raw exception if unchecked orError
-
newInternal
Deprecated.Throw newAssertionError
if applicable; orRuntimeException
if e is checked; or raw exception if e is unchecked orError
. -
throwIfUnchecked
Deprecated.AsThrowables.throwIfUnchecked(Throwable)
. -
throwAsRuntime
@API(since="1.26", status=EXPERIMENTAL) public static RuntimeException throwAsRuntime(Throwable throwable) This method rethrows input throwable as is (if its unchecked) or wraps it withRuntimeException
and throws.The typical usage would be
throw throwAsRuntime(...)
, wherethrow
statement is needed so Java compiler knows the execution stops at that line.- Parameters:
throwable
- input throwable- Returns:
- the method never returns, it always throws an unchecked exception
-
throwAsRuntime
@API(since="1.26", status=EXPERIMENTAL) public static RuntimeException throwAsRuntime(String message, Throwable throwable) This method rethrows input throwable as is (if its unchecked) with an extra message or wraps it withRuntimeException
and throws.The typical usage would be
throw throwAsRuntime(...)
, wherethrow
statement is needed so Java compiler knows the execution stops at that line.- Parameters:
throwable
- input throwable- Returns:
- the method never returns, it always throws an unchecked exception
-
toUnchecked
Wraps an exception withRuntimeException
and return it. If the exception is already an instance of RuntimeException, returns it directly. -
causeOrSelf
Returns cause of the given throwable if it is non-null or the throwable itself.- Parameters:
throwable
- input throwable- Returns:
- cause of the given throwable if it is non-null or the throwable itself
-
getMessages
Deprecated.Retrieves messages in a exception and writes them to a string. In the string returned, each message will appear on a different line.- Returns:
- a non-null string containing all messages of the exception
-
getStackTrace
Deprecated.UseThrowables.getStackTraceAsString(Throwable)
Returns the stack trace of a throwable. Called from native code.- Parameters:
t
- Throwable- Returns:
- Stack trace
-
pre
Deprecated.UsePreconditions.checkArgument(boolean)
orObjects.requireNonNull(Object)
-
post
Deprecated.UsePreconditions.checkArgument(boolean)
orObjects.requireNonNull(Object)
-
permAssert
Deprecated.UsePreconditions.checkArgument(boolean)
-
needToImplement
Returns aRuntimeException
indicating that a particular feature has not been implemented, but should be.If every 'hole' in our functionality uses this method, it will be easier for us to identify the holes. Throwing a
UnsupportedOperationException
isn't as good, because sometimes we actually want to partially implement an API.Example usage:
class MyVisitor extends BaseVisitor { void accept(Foo foo) { // Exception will identify which subclass forgot to override // this method throw Util.needToImplement(this); } }
- Parameters:
o
- The object which was the target of the call, or null. Passing the object gives crucial information if a method needs to be overridden and a subclass forgot to do so.- Returns:
- an
UnsupportedOperationException
.
-
deprecated
public static <T> T deprecated(T argument, boolean fail) Deprecated.If a piece of code calls this method, it indicates that the code needs to be cleaned up.Flags a piece of code as needing to be cleaned up before you check in.Introduce a call to this method to indicate that a piece of code, or a javadoc comment, needs work before you check in. If you have an IDE which can easily trace references, this is an easy way to maintain a to-do list.
Checked-in code must never call this method: you must remove all calls/references to this method before you check in.
The
argument
has generic type and determines the type of the result. This allows you to use the method inside an expression, for exampleint x = Util.deprecated(0, false);
but the usual usage is to pass in a descriptive string.
Examples
Example #1: Using
deprecated
to fail if a piece of supposedly dead code is reachedvoid foo(int x) { if (x < 0) { // If this code is executed, an error will be thrown. Util.deprecated( "no longer need to handle negative numbers", true); bar(x); } else { baz(x); } }
Example #2: Using
deprecated
to comment out dead codeif (Util.deprecated(false, false)) { // This code will not be executed, but an error will not be thrown. baz(); }
- Parameters:
argument
- Arbitrary argument to the method.fail
- Whether to throw an exception if this method is called- Returns:
- The value of the
argument
.
-
contains
Returns whether an array of strings contains a given string among the firstlength
entries.- Parameters:
a
- Array of stringslength
- Number of entries to searchs
- String to seek- Returns:
- Whether array contains the name
-
readAllAsString
Deprecated.Reads all remaining contents from aReader
and returns them as a string.- Parameters:
reader
- reader to read from- Returns:
- reader contents as string
- Throws:
IOException
-
squelchJar
Deprecated.Closes a Jar, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.- Parameters:
jar
- jar to close
-
squelchStream
Deprecated.Closes an InputStream, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.- Parameters:
stream
- stream to close
-
squelchStream
Deprecated.Closes an OutputStream, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception. If you want to make sure that data has been successfully flushed, do NOT use this anywhere else; use stream.close() instead.- Parameters:
stream
- stream to close
-
squelchReader
Deprecated.Closes a Reader, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.- Parameters:
reader
- reader to close
-
squelchWriter
Deprecated.Closes a Writer, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception. If you want to make sure that data has been successfully flushed, do NOT use this anywhere else; use writer.close() instead.- Parameters:
writer
- writer to close
-
squelchStmt
Deprecated.Closes a Statement, ignoring any SQL exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.- Parameters:
stmt
- stmt to close
-
squelchConnection
Deprecated.Closes a Connection, ignoring any SQL exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.- Parameters:
connection
- connection to close
-
rtrim
Deprecated.Trims trailing spaces from a string.- Parameters:
s
- string to be trimmed- Returns:
- trimmed string
-
rpad
Deprecated.UseSpaces.padRight(String, int)
Pads a string with spaces up to a given length.- Parameters:
s
- string to be paddedlen
- desired length- Returns:
- padded string
-
toString
Converts an iterable to a string. -
lines
Converts a list of strings to a string separated by newlines. -
tokenize
Converts a string into tokens. -
toPosix
Converts a Java timezone to POSIX format, so that the boost C++ library can instantiate timezone objects.POSIX IEEE 1003.1 defines a format for timezone specifications.
The boost C++ library can read these specifications and instantiate posix_time_zone objects from them. The purpose of this method, therefore, is to allow the C++ code such as the fennel calculator to use the same notion of timezone as Java code.
The format is as follows:
"std offset dst [offset],start[/time],end[/time]"
where:
- 'std' specifies the abbrev of the time zone.
- 'offset' is the offset from UTC, and takes the form
[+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}
- 'dst' specifies the abbrev of the time zone during daylight savings time
- The second offset is how many hours changed during DST. Default=1
- 'start' and 'end' are the dates when DST goes into (and out of)
effect. They can each be one of three forms:
- Mm.w.d {month=1-12, week=1-5 (5 is always last), day=0-6}
- Jn {n=1-365 Feb29 is never counted}
- n {n=0-365 Feb29 is counted in leap years}
- 'time' has the same format as 'offset', and defaults to 02:00:00.
For example:
- "PST-8PDT01:00:00,M4.1.0/02:00:00,M10.1.0/02:00:00"; or more tersely
- "PST-8PDT,M4.1.0,M10.1.0"
(Real format strings do not contain spaces; they are in the above template only for readability.)
Boost apparently diverges from the POSIX standard in how it treats the sign of timezone offsets. The POSIX standard states 'If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west', yet boost requires the opposite. For instance, PST has offset '-8' above. This method generates timezone strings consistent with boost's expectations.
- Parameters:
tz
- Timezoneverbose
- Whether to include fields which can be omitted because they have their default values- Returns:
- Timezone in POSIX format (offset sign reversed, per boost's idiosyncracies)
-
parseLocale
Parses a locale string.The inverse operation of
Locale.toString()
.- Parameters:
localeString
- Locale string, e.g. "en" or "en_US"- Returns:
- Java locale object
-
cast
Converts a list whose members are automatically down-cast to a given type.If a member of the backing list is not an instanceof
E
, the accessing method (such asList.get(int)
) will throw aClassCastException
.All modifications are automatically written to the backing list. Not synchronized.
- Parameters:
list
- Backing list.clazz
- Class to cast to.- Returns:
- A list whose members are of the desired type.
-
cast
public static <E extends @PolyNull Object> Iterator<E> cast(Iterator<? extends @PolyNull Object> iter, Class<E> clazz) Converts a iterator whose members are automatically down-cast to a given type.If a member of the backing iterator is not an instance of
E
,Iterator.next()
) will throw aClassCastException
.All modifications are automatically written to the backing iterator. Not synchronized.
If the backing iterator has not-nullable elements, the returned iterator has not-nullable elements.
- Parameters:
iter
- Backing iteratorclazz
- Class to cast to- Returns:
- An iterator whose members are of the desired type.
-
cast
Converts anIterable
whose members are automatically down-cast to a given type.All modifications are automatically written to the backing iterator. Not synchronized.
- Parameters:
iterable
- Backing iterableclazz
- Class to cast to- Returns:
- An iterable whose members are of the desired type.
-
filter
Makes a collection of untyped elements appear as a list of strictly typed elements, by filtering out those which are not of the correct type.The returned object is an
Iterable
, which makes it ideal for use with the 'foreach' construct. For example,List<Number> numbers = Arrays.asList(1, 2, 3.14, 4, null, 6E23); for (int myInt : filter(numbers, Integer.class)) { print(i); }
will print 1, 2, 4.
- Parameters:
iterable
- IterableincludeFilter
- Class whose instances to include
-
filter
-
filter
Returns a subset of a list containing only elements of a given type.Modifications to the list are NOT written back to the source list.
- Parameters:
list
- List of objectsincludeFilter
- Class to filter for- Returns:
- List of objects of given class (or a subtype)
-
toMap
Converts aProperties
object to a
.Map
<String, String>This is necessary because
Properties
is a dinosaur class. It ought to extendMap<String,String>
, but instead extends
.Hashtable
<Object,Object>Typical usage, to iterate over a
Properties
:Properties properties;
for (Map.Entry<String, String> entry = Util.toMap(properties).entrySet()) {
println("key=" + entry.getKey() + ", value=" + entry.getValue());
} -
mapOf
Returns a hashmap with given contents.Use this method in initializers. Type parameters are inferred from context, and the contents are initialized declaratively. For example,
Map<String, Integer> population =
Olap4jUtil.mapOf(
"UK", 65000000,
"USA", 300000000);- Type Parameters:
K
- Key typeV
- Value type- Parameters:
key
- First keyvalue
- First valuekeyValues
- Second and sequent key/value pairs- Returns:
- Map with given contents
-
unexpected
Returns an exception indicating that we didn't expect to find this enumeration here.- Parameters:
value
- Enumeration value which was not expected- Returns:
- an error, to be thrown
-
enumConstants
Creates a map of the values of an enumeration by name.- Parameters:
clazz
- Enumeration class- Returns:
- map of values
-
enumVal
Returns the value of an enumeration with a particular name.Similar to
Enum.valueOf(Class, String)
, but returnsnull
rather than throwingIllegalArgumentException
.- Type Parameters:
T
- Enum class type- Parameters:
clazz
- Enum classname
- Name of enum constant- Returns:
- Enum constant or null
-
enumVal
Returns the value of an enumeration with a particular or default value if not found.- Type Parameters:
T
- Enum class type- Parameters:
default_
- Default value (not null)name
- Name of enum constant- Returns:
- Enum constant, never null
-
quotientList
Creates a list that returns everyn
th element of a list, starting at elementk
.It is OK if the list is empty or its size is not a multiple of
n
.For instance,
quotientList(list, 2, 0)
returns the even elements of a list, andquotientList(list, 2, 1)
returns the odd elements. Those lists are the same length only if list has even size. -
pairs
Given a list with N elements [e0, e1, ..., eN-1] (where N is even), returns a list of the N / 2 elements [ (e0, e1), (e2, e3), ... ]. -
first
public static <T> @PolyNull T first(@Nullable T v0, @PolyNull T v1) Returns the first value if it is not null, otherwise the second value.The result may be null only if the second argument is not null.
Equivalent to the Elvis operator (
?:
) of languages such as Groovy or PHP. -
first
Unboxes aDouble
value, using a given default value if it is null. -
first
Unboxes aFloat
value, using a given default value if it is null. -
first
Unboxes aInteger
value, using a given default value if it is null. -
first
Unboxes aLong
value, using a given default value if it is null. -
first
Unboxes aBoolean
value, using a given default value if it is null. -
first
Unboxes aShort
value, using a given default value if it is null. -
first
Unboxes aCharacter
value, using a given default value if it is null. -
first
Unboxes aByte
value, using a given default value if it is null. -
orEmpty
-
first
Returns the first element of a list.- Throws:
IndexOutOfBoundsException
- if the list is empty
-
last
Returns the last element of a list.- Throws:
IndexOutOfBoundsException
- if the list is empty
-
first
Returns the firstn
elements of a list. -
skipLast
Returns every element of a list but its last element. -
skipLast
Returns every element of a list but its lastn
elements. -
last
Returns the lastn
elements of a list. -
skip
Returns all but the first element of a list. -
skip
Returns all but the firstn
elements of a list. -
range
-
range
-
isDistinct
Returns whether the elements oflist
are distinct. -
firstDuplicate
Returns the ordinal of the first element in the list which is equal to a previous element in the list.For example,
firstDuplicate(Arrays.asList("a", "b", "c", "b", "a"))
returns 3, the ordinal of the 2nd "b".- Parameters:
list
- List- Returns:
- Ordinal of first duplicate, or -1 if not found
-
isDefinitelyDistinctAndNonNull
Returns whether the elements oflist
are definitely distinct and not null, working quickly and sometimes giving false negatives for large lists.A return of true means that the list is distinct (true positive); a return of false means either that list is not distinct (true negative) or that the list is large and distinct (false negative). (If the list is large, a hash map would be required to do an accurate job, and this method does its best quickly.)
-
distinctList
Converts a list into a list with unique elements.The order is preserved; the second and subsequent occurrences are removed.
If the list is already unique it is returned unchanged.
-
distinctList
Converts an iterable into a list with unique elements.The order is preserved; the second and subsequent occurrences are removed.
If
iterable
is a unique list it is returned unchanged. -
intersects
Returns whether two collections have any elements in common. -
findMatch
Looks for a string within a list of strings, using a given case-sensitivity policy, and returns the position at which the first match is found, or -1 if there are no matches. -
matches
Returns whether a name matches another according to a given case-sensitivity policy. -
startsWith
Returns whether one list is a prefix of another. -
listToString
Converts ["ab", "c"] to "ab"."c". -
stringToList
-
human
Converts a number into human-readable form, with 3 digits and a "K", "M" or "G" multiplier for thousands, millions or billions.Examples: -2, 0, 1, 999, 1.00K, 1.99K, 3.45M, 4.56B.
-
asIndexMapJ
Returns a map that is a view onto a collection of values, using the provided function to convert a value to a key.Unlike
Maps.uniqueIndex(Iterable, com.google.common.base.Function)
, returns a view whose contents change as the collection of values changes.- Type Parameters:
K
- Key typeV
- Value type- Parameters:
values
- Collection of valuesfunction
- Function to map value to key- Returns:
- Map that is a view onto the values
-
asIndexMap
@Deprecated public static <K,V> Map<K,V> asIndexMap(Collection<V> values, com.google.common.base.Function<V, K> function) Deprecated. -
debugCode
Prints the given code with line numbering. -
immutableCopy
Returns a copy of a list of lists, making the component lists immutable if they are not already. -
printWriter
Creates aPrintWriter
to a given output stream using UTF-8 character set.Does not use the default character set.
-
printWriter
Creates aPrintWriter
to a given file using UTF-8 character set.Does not use the default character set.
- Throws:
FileNotFoundException
-
reader
Creates aBufferedReader
to a given input stream using UTF-8 character set.Does not use the default character set.
-
reader
Creates aBufferedReader
to read a given file using UTF-8 character set.Does not use the default character set.
- Throws:
FileNotFoundException
-
asStringBuilder
Given anAppendable
, performs an action that requires aStringBuilder
. Casts the Appendable if possible. -
calendar
Creates aCalendar
in the UTC time zone and root locale. -
calendar
Creates aCalendar
in the UTC time zone and root locale with a given time. -
calendar
Creates aCalendar
in the specified time zone. -
toImmutableList
@Deprecated public static <T> Collector<T,?, toImmutableList()com.google.common.collect.ImmutableList<T>> Deprecated.UseImmutableList.toImmutableList()
Returns aCollector
that accumulates the input elements into a GuavaImmutableList
via aImmutableList.Builder
. -
combine
public static <E> com.google.common.collect.ImmutableList.Builder<E> combine(com.google.common.collect.ImmutableList.Builder<E> b0, com.google.common.collect.ImmutableList.Builder<E> b1) Combines a second immutable list builder into a first. -
combine
Combines a second array list into a first. -
andThen
Returns an operator that appliesop1
and thenop2
.As
Function.andThen(Function)
but forUnaryOperator
. -
transform
public static <F,T> List<T> transform(List<? extends F> list, Function<? super F, ? extends T> function) Transforms a list, applying a function to each element. -
transformIndexed
public static <F,T> List<T> transformIndexed(List<? extends F> list, BiFunction<? super F, Integer, ? extends T> function) Transforms a list, applying a function to each element, also passing in the element's index in the list. -
transform
@API(since="1.27", status=EXPERIMENTAL) public static <F,T> Iterable<T> transform(Iterable<? extends F> iterable, Function<? super F, ? extends T> function) Transforms an iterable, applying a function to each element. -
transform
@API(since="1.27", status=EXPERIMENTAL) public static <F,T> Iterator<T> transform(Iterator<? extends F> iterator, Function<? super F, ? extends T> function) Transforms an iterator. -
filter
@API(since="1.27", status=EXPERIMENTAL) public static <E> Iterable<E> filter(Iterable<? extends E> iterable, Predicate<? super E> predicate) Filters an iterable. -
filter
@API(since="1.27", status=EXPERIMENTAL) public static <E> Iterator<E> filter(Iterator<? extends E> iterator, Predicate<? super E> predicate) Filters an iterator. -
moveToHead
Returns a list with any elements for which the predicate is true moved to the head of the list. The algorithm does not modify the list, is stable, and is idempotent. -
select
Returns a view of a list, picking the elements of a list with the given set of ordinals. -
blackholeMap
Returns a map which ignores any write operation.
-