Class Longs
long primitives, that are not already found in
 either Long or Arrays.
 See the Guava User Guide article on primitive utilities.
- Since:
- 1.0
- Author:
- Kevin Bourrillion
- 
Field SummaryFieldsModifier and TypeFieldDescriptionstatic final intThe number of bytes required to represent a primitivelongvalue.static final longThe largest power of two that can be represented as along.
- 
Method SummaryModifier and TypeMethodDescriptionasList(long... backingArray) Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[]).static intcompare(long a, long b) Compares the two specifiedlongvalues.static long[]concat(long[]... arrays) Returns the values from each provided array combined into a single array.static longconstrainToRange(long value, long min, long max) Returns the value nearest tovaluewhich is within the closed range[min..max].static booleancontains(long[] array, long target) Returnstrueiftargetis present as an element anywhere inarray.static long[]ensureCapacity(long[] array, int minLength, int padding) Returns an array containing the same values asarray, but guaranteed to be of a specified minimum length.static longfromByteArray(byte[] bytes) Returns thelongvalue whose big-endian representation is stored in the first 8 bytes ofbytes; equivalent toByteBuffer.wrap(bytes).getLong().static longfromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) Returns thelongvalue whose byte representation is the given 8 bytes, in big-endian order; equivalent toLongs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8}).static inthashCode(long value) Returns a hash code forvalue; obsolete alternative toLong.hashCode(long).static intindexOf(long[] array, long target) Returns the index of the first appearance of the valuetargetinarray.static intindexOf(long[] array, long[] target) Returns the start position of the first occurrence of the specifiedtargetwithinarray, or-1if there is no such occurrence.static StringReturns a string containing the suppliedlongvalues separated byseparator.static intlastIndexOf(long[] array, long target) Returns the index of the last appearance of the valuetargetinarray.static Comparator<long[]> Returns a comparator that compares twolongarrays lexicographically.static longmax(long... array) Returns the greatest value present inarray.static longmin(long... array) Returns the least value present inarray.static voidreverse(long[] array) Reverses the elements ofarray.static voidreverse(long[] array, int fromIndex, int toIndex) Reverses the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive.static voidrotate(long[] array, int distance) Performs a right rotation ofarrayof "distance" places, so that the first element is moved to index "distance", and the element at indexiends up at index(distance + i) mod array.length.static voidrotate(long[] array, int distance, int fromIndex, int toIndex) Performs a right rotation ofarraybetweenfromIndexinclusive andtoIndexexclusive.static voidsortDescending(long[] array) Sorts the elements ofarrayin descending order.static voidsortDescending(long[] array, int fromIndex, int toIndex) Sorts the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive in descending order.Returns a serializable converter object that converts between strings and longs usingLong.decode(java.lang.String)andLong.toString().static long[]toArray(Collection<? extends Number> collection) Returns an array containing each value ofcollection, converted to alongvalue in the manner ofNumber.longValue().static byte[]toByteArray(long value) Returns a big-endian representation ofvaluein an 8-element byte array; equivalent toByteBuffer.allocate(8).putLong(value).array().Parses the specified string as a signed decimal long value.Parses the specified string as a signed long value using the specified radix.
- 
Field Details- 
BYTESpublic static final int BYTESThe number of bytes required to represent a primitivelongvalue.Prefer Long.BYTESinstead.- See Also:
 
- 
MAX_POWER_OF_TWOpublic static final long MAX_POWER_OF_TWOThe largest power of two that can be represented as along.- Since:
- 10.0
- See Also:
 
 
- 
- 
Method Details- 
hashCodeReturns a hash code forvalue; obsolete alternative toLong.hashCode(long).- Parameters:
- value- a primitive- longvalue
- Returns:
- a hash code for the value
 
- 
compareCompares the two specifiedlongvalues. The sign of the value returned is the same as that of((Long) a).compareTo(b).Note: this method is now unnecessary and should be treated as deprecated; use the equivalent Long.compare(long, long)method instead.- Parameters:
- a- the first- longto compare
- b- the second- longto compare
- Returns:
- a negative value if ais less thanb; a positive value ifais greater thanb; or zero if they are equal
 
- 
containspublic static boolean contains(long[] array, long target) Returnstrueiftargetis present as an element anywhere inarray.- Parameters:
- array- an array of- longvalues, possibly empty
- target- a primitive- longvalue
- Returns:
- trueif- array[i] == targetfor some value of- i
 
- 
indexOfpublic static int indexOf(long[] array, long target) Returns the index of the first appearance of the valuetargetinarray.- Parameters:
- array- an array of- longvalues, possibly empty
- target- a primitive- longvalue
- Returns:
- the least index ifor whicharray[i] == target, or-1if no such index exists.
 
- 
indexOfpublic static int indexOf(long[] array, long[] target) Returns the start position of the first occurrence of the specifiedtargetwithinarray, or-1if there is no such occurrence.More formally, returns the lowest index isuch thatArrays.copyOfRange(array, i, i + target.length)contains exactly the same elements astarget.- Parameters:
- array- the array to search for the sequence- target
- target- the array to search for as a sub-sequence of- array
 
- 
lastIndexOfpublic static int lastIndexOf(long[] array, long target) Returns the index of the last appearance of the valuetargetinarray.- Parameters:
- array- an array of- longvalues, possibly empty
- target- a primitive- longvalue
- Returns:
- the greatest index ifor whicharray[i] == target, or-1if no such index exists.
 
- 
minpublic static long min(long... array) Returns the least value present inarray.- Parameters:
- array- a nonempty array of- longvalues
- Returns:
- the value present in arraythat is less than or equal to every other value in the array
- Throws:
- IllegalArgumentException- if- arrayis empty
 
- 
maxpublic static long max(long... array) Returns the greatest value present inarray.- Parameters:
- array- a nonempty array of- longvalues
- Returns:
- the value present in arraythat is greater than or equal to every other value in the array
- Throws:
- IllegalArgumentException- if- arrayis empty
 
- 
constrainToRangepublic static long constrainToRange(long value, long min, long max) Returns the value nearest tovaluewhich is within the closed range[min..max].If valueis within the range[min..max],valueis returned unchanged. Ifvalueis less thanmin,minis returned, and ifvalueis greater thanmax,maxis returned.Java 21+ users: Use Math.clampinstead. Note that that method is capable of constraining alonginput to anintrange.- Parameters:
- value- the- longvalue to constrain
- min- the lower bound (inclusive) of the range to constrain- valueto
- max- the upper bound (inclusive) of the range to constrain- valueto
- Throws:
- IllegalArgumentException- if- min > max
- Since:
- 21.0
 
- 
concatpublic static long[] concat(long[]... arrays) Returns the values from each provided array combined into a single array. For example,concat(new long[] {a, b}, new long[] {}, new long[] {c}returns the array{a, b, c}.- Parameters:
- arrays- zero or more- longarrays
- Returns:
- a single array containing all the values from the source arrays, in order
- Throws:
- IllegalArgumentException- if the total number of elements in- arraysdoes not fit in an- int
 
- 
toByteArraypublic static byte[] toByteArray(long value) Returns a big-endian representation ofvaluein an 8-element byte array; equivalent toByteBuffer.allocate(8).putLong(value).array(). For example, the input value0x1213141516171819Lwould yield the byte array{0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}.If you need to convert and concatenate several values (possibly even of different types), use a shared ByteBufferinstance, or useByteStreams.newDataOutput()to get a growable buffer.
- 
fromByteArraypublic static long fromByteArray(byte[] bytes) Returns thelongvalue whose big-endian representation is stored in the first 8 bytes ofbytes; equivalent toByteBuffer.wrap(bytes).getLong(). For example, the input byte array{0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}would yield thelongvalue0x1213141516171819L.Arguably, it's preferable to use ByteBuffer; that library exposes much more flexibility at little cost in readability.- Throws:
- IllegalArgumentException- if- byteshas fewer than 8 elements
 
- 
fromBytespublic static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) Returns thelongvalue whose byte representation is the given 8 bytes, in big-endian order; equivalent toLongs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8}).- Since:
- 7.0
 
- 
tryParseParses the specified string as a signed decimal long value. The ASCII character'-'('\u002D') is recognized as the minus sign.Unlike Long.parseLong(String), this method returnsnullinstead of throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returnsnullif non-ASCII digits are present in the string.Note that strings prefixed with ASCII '+'are rejected, even thoughInteger.parseInt(String)accepts them.- Parameters:
- string- the string representation of a long value
- Returns:
- the long value represented by string, ornullifstringhas a length of zero or cannot be parsed as a long value
- Throws:
- NullPointerException- if- stringis- null
- Since:
- 14.0
 
- 
tryParseParses the specified string as a signed long value using the specified radix. The ASCII character'-'('\u002D') is recognized as the minus sign.Unlike Long.parseLong(String, int), this method returnsnullinstead of throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returnsnullif non-ASCII digits are present in the string.Note that strings prefixed with ASCII '+'are rejected, even thoughInteger.parseInt(String)accepts them.- Parameters:
- string- the string representation of a long value
- radix- the radix to use when parsing
- Returns:
- the long value represented by stringusingradix, ornullifstringhas a length of zero or cannot be parsed as a long value
- Throws:
- IllegalArgumentException- if- radix < Character.MIN_RADIXor- radix > Character.MAX_RADIX
- NullPointerException- if- stringis- null
- Since:
- 19.0
 
- 
stringConverterReturns a serializable converter object that converts between strings and longs usingLong.decode(java.lang.String)andLong.toString(). The returned converter throwsNumberFormatExceptionif the input string is invalid.Warning: please see Long.decode(java.lang.String)to understand exactly how strings are parsed. For example, the string"0123"is treated as octal and converted to the value83L.- Since:
- 16.0
 
- 
ensureCapacitypublic static long[] ensureCapacity(long[] array, int minLength, int padding) Returns an array containing the same values asarray, but guaranteed to be of a specified minimum length. Ifarrayalready has a length of at leastminLength, it is returned directly. Otherwise, a new array of sizeminLength + paddingis returned, containing the values ofarray, and zeroes in the remaining places.- Parameters:
- array- the source array
- minLength- the minimum length the returned array must guarantee
- padding- an extra amount to "grow" the array by if growth is necessary
- Returns:
- an array containing the values of array, with guaranteed minimum lengthminLength
- Throws:
- IllegalArgumentException- if- minLengthor- paddingis negative
 
- 
joinReturns a string containing the suppliedlongvalues separated byseparator. For example,join("-", 1L, 2L, 3L)returns the string"1-2-3".- Parameters:
- separator- the text that should appear between consecutive values in the resulting string (but not at the start or end)
- array- an array of- longvalues, possibly empty
 
- 
lexicographicalComparatorReturns a comparator that compares twolongarrays lexicographically. That is, it compares, usingcompare(long, long)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example,[] < [1L] < [1L, 2L] < [2L].The returned comparator is inconsistent with Object.equals(Object)(since arrays support only identity equality), but it is consistent withArrays.equals(long[], long[]).- Since:
- 2.0
 
- 
sortDescendingpublic static void sortDescending(long[] array) Sorts the elements ofarrayin descending order.- Since:
- 23.1
 
- 
sortDescendingpublic static void sortDescending(long[] array, int fromIndex, int toIndex) Sorts the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive in descending order.- Since:
- 23.1
 
- 
reversepublic static void reverse(long[] array) Reverses the elements ofarray. This is equivalent toCollections.reverse(Longs.asList(array)), but is likely to be more efficient.- Since:
- 23.1
 
- 
reversepublic static void reverse(long[] array, int fromIndex, int toIndex) Reverses the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive. This is equivalent toCollections.reverse(Longs.asList(array).subList(fromIndex, toIndex)), but is likely to be more efficient.- Throws:
- IndexOutOfBoundsException- if- fromIndex < 0,- toIndex > array.length, or- toIndex > fromIndex
- Since:
- 23.1
 
- 
rotatepublic static void rotate(long[] array, int distance) Performs a right rotation ofarrayof "distance" places, so that the first element is moved to index "distance", and the element at indexiends up at index(distance + i) mod array.length. This is equivalent toCollections.rotate(Longs.asList(array), distance), but is considerably faster and avoids allocation and garbage collection.The provided "distance" may be negative, which will rotate left. - Since:
- 32.0.0
 
- 
rotatepublic static void rotate(long[] array, int distance, int fromIndex, int toIndex) Performs a right rotation ofarraybetweenfromIndexinclusive andtoIndexexclusive. This is equivalent toCollections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance), but is considerably faster and avoids allocations and garbage collection.The provided "distance" may be negative, which will rotate left. - Throws:
- IndexOutOfBoundsException- if- fromIndex < 0,- toIndex > array.length, or- toIndex > fromIndex
- Since:
- 32.0.0
 
- 
toArrayReturns an array containing each value ofcollection, converted to alongvalue in the manner ofNumber.longValue().Elements are copied from the argument collection as if by collection.toArray(). Calling this method is as thread-safe as calling that method.- Parameters:
- collection- a collection of- Numberinstances
- Returns:
- an array containing the same values as collection, in the same order, converted to primitives
- Throws:
- NullPointerException- if- collectionor any of its elements is null
- Since:
- 1.0 (parameter was Collection<Long>before 12.0)
 
- 
asListReturns a fixed-size list backed by the specified array, similar toArrays.asList(Object[]). The list supportsList.set(int, Object), but any attempt to set a value tonullwill result in aNullPointerException.The returned list maintains the values, but not the identities, of Longobjects written to or read from it. For example, whetherlist.get(0) == list.get(0)is true for the returned list is unspecified.The returned list is serializable. Note: when possible, you should represent your data as an ImmutableLongArrayinstead, which has anasListview.- Parameters:
- backingArray- the array to back the list
- Returns:
- a list view of the array
 
 
-