# Java Utils
# Arrays
java.util.Arrays- conversion
asList(T... a)—return new ArrayList<>(a);ArrayListhere isArrays$ArrayListwhich implementsList, a view on the original array with fixed size- if real
ArrayListis desired — use thisArrays$ArrayListto construct
- stream methods
static int binarySearch(type[] a, type v)
static int binarySearch(type[] a, int start, int end, type v)Object[]is required to beComparable[]
- copy
copyOf(type[] original, int newLength)— usesSystem::arraycopybehind the scenescopyOfRange(type[] a, int start, int end)System::arraycopyT[]::clone
- initialization and modifications
fill(type[] a, type v)setAll— generator takes indices as parameterparallelSetAll— parallel version ofsetAllparallelPrefix— prefix operators, like prefix sum
ObjectmethodstoString-deepToStringequals-deepEqualshashCode-deepHashCodecompare— since JDK 9
- sort —
java.util.DualPivotQuickSort::sortfor primitive type arrays,java.util.TimSort::sortfor othersstatic void sort(type[] a)
static void sort(type[] a, int fromIndex, int toIndex)
static <T> void sort(T[] a, Comparator<? super T> c)
static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)Object[]actually needs to beComparable[]
parallelSort- sequential sort (as
Arrays::sort) whenif (n <= MIN_ARRAY_SORT_GRAN || (p = ForkJoinPool.getCommonPoolParallelism()) == 1)- granularity —
private static final int MIN_ARRAY_SORT_GRAN = 1 << 13;
- granularity —
- else parallel sort — uses
ForkJoinPool(each thread gets a chunk of the list and sorts it in parallel. Later these sorted chunks are merged into a result)
- sequential sort (as
- conversion
# Event Handling
java.util.EventListener— A tagging interface that all event listener interfaces must extendjava.util.EventListenerProxy— An abstract wrapper class for an EventListener class which associates a set of additional parameters with the listenerpublic abstract class EventListenerProxy<T extends EventListener> extends Object implements EventListenerjava.util.EventObject— The root class from which all event state objects shall be derivedpublic class EventObject extends Object implements Serializableobserver —
java.util.Observable,interface java.util.Observer- deprecated since JDK 9 — the event model supported by
ObserverandObservableis quite limited, the order of notifications delivered byObservableis unspecified, and state changes are not in one-for-one correspondence with notifications - for a richer event model, consider using the
java.beans - for reactive streams style —
java.util.concurrent.Flow
- deprecated since JDK 9 — the event model supported by
# Collections and Maps
concurrent collections — see Thread-Safe Collections
interface java.lang.Iterable<T>default void forEach(Consumer<? super T> action)Iterator<T> iterator()default Spliterator<T> spliterator()- foreach loop — needs to implement
Iterable- behind the scenes — a loop with an iterator
interface java.util.Iterator<E>- fail fast — multiple readers, or a single reader and writer, otherwise
ConcurrentModificationException- detection scheme — the count of modifications is keep in both the collection and the iterator
- exception —
LinkedList::setis not counted
E next()— possiblyNoSuchElementExceptionboolean hasNext()void remove()— remove the element last returned bynext()default void forEachRemaining(Consumer<? super E> action)Collections::emptyIterator
- fail fast — multiple readers, or a single reader and writer, otherwise
java.util.Spliterator— both sequential and parallel data processing, the parallel analogue of anIterator- fail fast
- late-binding — binds to the source of elements at the point of first traversal, first split, or first query for estimated size, rather than at the time the
Spliteratoris created
java.util.Collectionpublic interface Collection<E> extends Iterable<E>- add
boolean add(E e)—truewhen successboolean addAll(Collection<? extends E> c)— returntrueif the collection changed
- test
boolean equals(Object o)boolean contains(Object o)boolean containsAll(Collection<?> c)boolean isEmpty()
- modify
void clear()boolean removeIf(Predicate<? super E> filter)boolean removeAll(Collection<?> c)boolean remove(Object o)boolean retainAll(Collection<?> c)
- conversion
<T> T[] toArray(T[] a)— no new array created ifais of the correct size, recommended to use a zero-size one in case of concurrent modificationsdefault Stream<E> stream()default Stream<E> parallelStream()
- get collection information
int size()Iterator<E> iterator()default Spliterator<E> spliterator()
java.util.AbstractCollection— a skeletal implementation of theCollectioninterface, to minimize the effort required to implement this interfacepublic abstract class AbstractCollection<E> implements Collection<E>- should have been replaced by default methods, but only new methods have default implementation
- extends the abstract class and simultaneously implement the interface — only make a difference to clarity and reflection
- add
java.util.Collections— static helperaddAll(Collection<? super T> c, T... elements)— returntrueif the collection changeddisjoint(Collection<?> c1, Collection<?> c2)—trueif the two specified collections have no elements in commonfrequency(Collection<?> c, Object o)min,max— supportComparatorstatic <T> Comparator<T> reverseOrder()
static <T> Comparator<T> reverseOrder(Comparator<T> cmp)- called by
Comparator::reverseOrderandComparator::reversed
- called by
- list related — see List
- views and wrappers — see Views and Wrappers
Collections::unmodifiableCollectionCollections::synchronizedCollectionCollections::checkedCollection
# List
interface java.util.RandomAccess— marker interface used byListimplementations to indicate that they support fast (generally constant time) random accessjava.util.Listpublic interface List<E> extends Collection<E>java.util.AbstractList<E>— This class provides a skeletal implementation of theListinterface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array)public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>- add — with indexed version
void add(int index, E element)boolean addAll(int index, Collection<? extends E> c)
- element
E get(int index)int indexOf()int lastIndexOf(Object o)
- list information
ListIterator<E> listIterator()ListIterator<E> listIterator(int index)default Spliterator<E> spliterator()List<E> subList(int fromIndex, int toIndex)— a view
- modify and converse
E set(int index, E element)E remove(int index)default void sort(Comparator<? super E> c)— usesArrays::sortaftertoArray()
java.util.ListIterator— haspreviousin addition tonextpublic interface ListIterator<E> extends Iterator<E>void add(E e)boolean hasPrevious()int nextIndex()E previous()int previousIndex()void set(E e)Collections::emptyListIterator
Collectionsmethods related toList- find
binarySearch(List<? extends Comparable<? super T>> list, T key)— return(-(insertion point) - 1)if no matching
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)- whether
indexedBinarySearchoriteratorBinarySearch— checksRandomAccessorBINARYSEARCH_THRESHOLDto determine
- whether
indexOfSubList(List<?> source, List<?> target)lastIndexOfSubList(List<?> source, List<?> target)
- modify
copy(List<? super T> dest, List<? extends T> src)fill(List<? super T> list, T obj)static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)reverse(List<?> list)rotate(List<?> list, int distance)shuffle(List<?> list)— checks whetherRandomAccessotherwisetoArray()
shuffle(List<?> list, Random rnd)sort(List<T> list)
sort(List<T> list, Comparator<? super T> c)— usesList::sort, consider usingArrayList::sortif possibleswap(List<?> list, int i, int j)
- views
Arrays::asListnCopiessingletonListemptyListunmodifiableListsynchronizedListcheckedListList::subList
- find
java.util.ArrayListpublic class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializableprivate static final int DEFAULT_CAPACITY = 10- constructors
ArrayList()— constructs an empty list with an initial capacity of 10ArrayList(Collection<? extends E> c)ArrayList(int initialCapacity)- anonymous
ArrayList— double brace initialization, actually a inner subclassnew ArrayList<String>() {{ add("Harry"); add("Tony"); }}; int[]toArrayList<Integer>without loop — for large arrays with sparse access patternspublic List<Integer> asList(final int[] is) { return Collections.unmodifiableList(new AbstractList<Integer>() { public Integer get(int i) { return is[i]; } public int size() { return is.length; } }); }
- capacity
void ensureCapacity(int minCapacity)int newCapacity = oldCapacity + (oldCapacity >> 1);void trimToSize()
java.util.LinkedListpublic class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable- use with
ListIterator LinkedListvsArrayDeque— seeArrayDequebelow
- use with
# Queue
java.util.Queuepublic interface Queue<E> extends Collection<E>IllegalStateExceptionorNoSuchElementExceptionwhen failureboolean add(E e)— returningtrueupon success and throwing anIllegalStateExceptionif no space is currently availableE remove()E element()— peek the head
- return
nullwhen failureboolean offer(E e)E poll()E peek()
java.util.AbstractQueue— skeletal implementations of someQueueoperationspublic abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E>
java.util.Dequepublic interface Deque<E> extends Queue<E>First Element (Head) Last Element (Tail) Throws exception return special value Throws exception return special value Insert addFirst(e),push(e)offerFirst(e)addLast(e),add(e)offerLast(e),offer(e)Remove removeFirst(),remove(),pop()pollFirst(),poll()removeLast()pollLast()Examine getFirst(),element()peekFirst(),peek()getLast()peekLast()- usage — double ended queue, also should be used in preference to the legacy
Stackclass
- usage — double ended queue, also should be used in preference to the legacy
LinkedList— seeListbeforejava.util.ArrayDequepublic class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable- underlying implementation — circular array
- not implementing
Listand extendsAbstractCollectionbut notAbstractQueue— retrofitArrayDequeto implementList(opens new window) - no
nullsupport —NullPointerExceptionfornullelements - capacity
- default initial capacity — 16
- capacity grow policy — double capacity if small; else grow by 50%
ArrayDequevsLinkedList—LinkedLists iterate with more CPU cache miss, have the overhead of node allocations, and consume more memory, but supportsList,nullelements, and better remove-while-iterate
java.util.PriorityQueuepublic class PriorityQueue<E> extends AbstractQueue<E> implements Serializableprivate static final int DEFAULT_INITIAL_CAPACITY = 11- capacity grow policy — as
ArrayDeque
views
- as stack —
Collections::asLifoQueue
- as stack —
# Set
java.util.Setpublic interface Set<E> extends Collection<E>java.util.AbstractSet<E>
java.util.NavigableSet— adds methods for locating and backward traversalpublic interface NavigableSet<E> extends SortedSet<E>- locating
E lower(E e)E pollFirst()E pollLast()E higher(E e)E ceiling(E e)E floor(E e)
- backward traversal
Iterator<E> descendingIterator()NavigableSet<E> descendingSet()
java.util.SortedSetpublic interface SortedSet<E> extends Set<E>Comparator<? super E> comparator()E first()E last()default Spliterator<E> spliterator()SortedSet<E> headSet(E toElement)SortedSet<E> subSet(E fromElement, E toElement)SortedSet<E> tailSet(E fromElement)
- locating
java.util.HashSetpublic class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable- underlying data structure —
private transient HashMap<E,Object> map - dummy value for the value of
Map.Entry—private static final Object PRESENT = new Object() - iteration performance — proportional to capability
- underlying data structure —
java.util.TreeSet— red-black treepublic class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable- underlying data structure —
private transient NavigableMap<E,Object> m, initialized withTreeMap - dummy value — see
HashSet
- underlying data structure —
java.util.EnumSet— for use with enum typespublic abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable- underlying data — represented internally as bit vectors
- no
nullsupport —NullPointerExceptionfornullelements - usage — a high-quality, typesafe alternative to traditional int-based "bit flags"
- underlying implementation —
RegularEnumSetwith along,JumboEnumSetwith along[], non-public injava.util - helper class — the abstract class itself acts as a static helper
java.util.LinkedHashSet— orderedHashSetwith underlying linked list, have no control overremoveEldestEntrypublic class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializableviews
Map::keySetetc.- set from map —
Collections::newSetFromMap(for maps without corresponding sets, likeWeakHashMapbut notHashMap) Collections::singleton- empty views —
Collections::emptySet,Collections::emptyNavigableSet,Collections::emptySortedSet - unmodifiable views —
Collections::unmodifiableSet,Collections::unmodifiableNavigableSet,Collections::unmodifiableSortedSet - synchronized views
- checked views
- subset methods
BitSet— see Legacy Collections
# Maps
java.util.Mappublic interface Map<K,V>- modify
void clear()- return old value if not
voidV remove(Object key)— returns the previous value ornulldefault boolean remove(Object key, Object value)— remove ifget(key)equalsvalueV put(K key, V value)— returns asremovemethoddefault V putIfAbsent(K key, V value)—nullvalue is also absentvoid putAll(Map<? extends K,? extends V> m)default V replace(K key, V value)default boolean replace(K key, V oldValue, V newValue)default void replaceAll(BiFunction<? super K,? super V,? extends V> function)
- return new value if not
voiddefault V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)default V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)—nullvalue is also absentdefault V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)default V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);// example counts.put(word, counts.getOrDefault(word, 0) + 1); counts.merge(word, 1, Integer::sum);
- test
boolean isEmpty()boolean containsKey(Object key)boolean containsValue(Object value)boolean equals(Object o)
- loop or views
default void forEach(BiConsumer<? super K,? super V> action)Set<Map.Entry<K,V>> entrySet()Set<K> keySet()Collection<V> values()
- get
V get(Object key)—nullif absent, can be confused withnullvaluesdefault V getOrDefault(Object key, V defaultValue)
int size()interface Entry<K, V>— key-value pairjava.util.AbstractMap<K,V>— This class provides a skeletal implementation of theMapinterface, to minimize the effort required to implement this interfacepublic abstract class AbstractMap<K,V> extends Object implements Map<K,V>- should have been replaced by default methods, but only new methods have default implementation
AbstractMap.SimpleEntry,AbstractMap.SimpleImmutableEntrypublic static class AbstractMap.SimpleEntry<K,V> extends Object implements Map.Entry<K,V>, Serializable
- modify
java.util.NavigableMap— refer toNavigableSetpublic interface NavigableMap<K,V> extends SortedMap<K,V>java.util.HashMappublic class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable- schema — hash code modulo the number of buckets, or red-black tree if a hash collision
- constants
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4— initial capacity will be converted to the power of 2static final int MAXIMUM_CAPACITY = 1 << 30static final float DEFAULT_LOAD_FACTOR = 0.75fstatic final int TREEIFY_THRESHOLD = 8static final int UNTREEIFY_THRESHOLD = 6static final int MIN_TREEIFY_CAPACITY = 64— smallest capability to permit treeify
static class Node<K,V> implements Map.Entry<K,V>— permitsnullvalues and keys- iteration performance — proportional to capability
java.util.TreeMap— red-black treepublic class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable- do not support the
Entry::setValuemethod — entries exported asAbstractMap.SimpleImmutableEntry<>(e)for most methods
- do not support the
java.util.EnumMap— for use with enum typespublic class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable- underlying data — represented internally as arrays, ordinals as indices
- weakly consistent iterators — never throw
ConcurrentModificationException, may or may not show the effects of any modifications to the map that occur while the iteration is in progress nullsupport — nonullkeys but values
java.util.LinkedHashMap— orderedHashMapwith underlying doubly-linked listpublic class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)final boolean accessOrder—truefor access order,falsefor insertion order (default)
- insertion order — the order is not affected if a key is re-inserted, even the value changes
- access order — get methods and modify methods make corresponding entries place at the last position:
put,putIfAbsent,get,getOrDefault,compute,computeIfAbsent,computeIfPresent, ormergeMap::replace— results an access only when the value is replaced- operations on views — no effect on order
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)— invoked byputandputAllafter inserting a new entry into the map, returnstrueif this map should remove its eldest entry
java.util.WeakHashMappublic class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>- underlying implementation —
EntryextendsWeakReferenceand registered to aReferenceQueueupon construction - GC unreachable — the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector
private final ReferenceQueue<Object> queue—WeakReferencekeys are registered with aqueuewhen created; seeReferenceQueueexpungeStaleEntries()— private method that scanWeakReferencekeys inqueueand set corresponding values tonull; called every time in access methods,size(), and internal resize method
nullsupport — both keys and values- values with strong reference to the keys — prevent keys from gc, can be alleviated by wrapping values with
new WeakReference(value)
- underlying implementation —
java.util.IdentityHashMap—HashMapwith keys (and values) that are compared by==, notequalspublic class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Serializable, Cloneable- underlying implementation — closed hashing, value placed next to key bucket, resize when
3 * size > len(load factor of 0.667) - constant-time performance for the basic operations (
getandput) — assuming the system identity hash function (System.identityHashCode(Object)) disperses elements properly among the buckets - rehashing may be fairly expensive — initialize with large expected capacity
- underlying implementation — closed hashing, value placed next to key bucket, resize when
map views
Collections::singletonMap- empty views —
Collections::emptyMap,Collections::emptyNavigableMap,Collections::emptySortedMap - unmodifiable views —
Collections::unmodifiableMap,Collections::unmodifiableNavigableMap,Collections::unmodifiableSortedMap - synchronized views
- checked views
- sub map methods
# Views and Wrappers
Map::keySetetc.Arrays::asListCollectionsviews and wrappers- one for n wrapper —
static <T> List<T> nCopies(int n, T o)- returns an immutable list consisting of n copies of the specified object,
ois stored only once
- returns an immutable list consisting of n copies of the specified object,
- stack view —
static <T> Queue<T> asLifoQueue(Deque<T> deque) - set view from map, see Set —
static <E> Set<E> newSetFromMap(Map<E,Boolean> map) - wrappers containing only one element — immutable, instance of inner class in
Collections, containing only one elementstatic <T> Set<T> singleton(T o)static <T> List<T> singletonList(T o)static <K,V> Map<K,V> singletonMap(K key, V value)
- empty wrapper — immutable, instance of inner class in
Collections, singletonstatic <T> Iterator<T> emptyIterator()static <T> List<T> emptyList()static <T> ListIterator<T> emptyListIterator()static <K,V> Map<K,V> emptyMap()static <K,V> NavigableMap<K,V> emptyNavigableMap()static <E> NavigableSet<E> emptyNavigableSet()static <T> Set<T> emptySet()static <K,V> SortedMap<K,V> emptySortedMap()static <E> SortedSet<E> emptySortedSet()
- unmodifiable view —
UnsupportedOperationExceptionwhen try modifying, instance of inner class inCollectionsstatic <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)static <T> List<T> unmodifiableList(List<? extends T> list)static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K,? extends V> m)static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)static <T> Set<T> unmodifiableSet(Set<? extends T> s)static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m)static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
- synchronized view — synchronized with mutex, instance of inner class in
Collectionsstatic <T> Collection<T> synchronizedCollection(Collection<T> c)static <T> List<T> synchronizedList(List<T> list)static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)static <T> Set<T> synchronizedSet(Set<T> s)static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
- checked view — throw
ClassCastExceptionimmediately when heap pollution (detects withClass::isInstance), instance of inner class inCollections, intended as debugging supportArrayList<String> strings = new ArrayList<>(); ArrayList rawList = strings; // warning only, not an error, for compatibility with legacy code rawList.add(new Date()); // now strings contains a Date object!static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)static <E> List<E> checkedList(List<E> list, Class<E> type)static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType)static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type)static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)static <E> Set<E> checkedSet(Set<E> s, Class<E> type)static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)
equalsandhashCodeof views and wrappers- unmodifiable, synchronized and checked views — returns a collection whose equals method does not invoke the
equalsmethod of the underlying collection butObject::equals, same forhashCode - exception —
unmodifiableSetandunmodifiableListmethods use theequalsandhashCodemethods of the underlying collections
- unmodifiable, synchronized and checked views — returns a collection whose equals method does not invoke the
- one for n wrapper —
sub-ranges — views that changes reflect to the original
List::subListSortedMap::subMap,SortedMap::headMap,SortedMap::tailMapNavigableMap— overrides and has new definitions with inclusion option- also for
SortedSetandNavigableSet
# Legacy Collections
java.util.Hashtable— synchronizedHashMap, useConcurrentHashMapinsteadjava.util.Properties— for property filespublic class Properties extends Hashtable<Object,Object>Stringkeys and values- property file syntax — .properties - Wikipedia (opens new window)
- can be saved to a stream or loaded from a stream
void store(OutputStream out, String comments)- more
- can use a secondary
Propertiesfor defaultProperties()Properties(Properties defaults)String getProperty(String key)String getProperty(String key, String defaultValue)—defaultValueonly when no secondaryPropertiesandkeyabsent
- system properties — see
javain CLI, find accessible names in$JAVA_HOME/conf/security/java.policy# jshell> System.getProperties().forEach((k, v) -> System.out.printf("%s=%s\n", k, v)) $ java -XshowSettings:properties --version Property settings: # only a portion is available on all platforms awt.toolkit = sun.awt.windows.WToolkit file.encoding = GBK # not an official property, use Charset.defaultCharset() instead file.separator = \ java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment java.class.path = java.class.version = 56.0 java.home = C:\Program Files\Java\jdk-12.0.2 java.io.tmpdir = C:\Users\ADMINI~1\AppData\Local\Temp\ java.library.path = # JAVA_PATH;C:\Windows\Sun\Java\bin;. for Windows java.runtime.name = OpenJDK Runtime Environment java.runtime.version = 12.0.2+10 java.specification.name = Java Platform API Specification java.specification.vendor = Oracle Corporation java.specification.version = 12 java.vendor = Oracle Corporation java.vendor.url = https://java.oracle.com/ java.vendor.url.bug = https://bugreport.java.com/bugreport/ java.version = 12.0.2 java.version.date = 2019-07-16 java.vm.compressedOopsMode = Zero based java.vm.info = mixed mode, sharing java.vm.name = OpenJDK 64-Bit Server VM java.vm.specification.name = Java Virtual Machine Specification java.vm.specification.vendor = Oracle Corporation java.vm.specification.version = 12 java.vm.vendor = Oracle Corporation java.vm.version = 12.0.2+10 jdk.debug = release line.separator = \r\n os.arch = amd64 os.name = Windows 7 os.version = 6.1 path.separator = ; sun.arch.data.model = 64 sun.boot.library.path = C:\Program Files\Java\jdk-12.0.2\bin sun.cpu.endian = little sun.cpu.isalist = amd64 sun.desktop = windows sun.io.unicode.encoding = UnicodeLittle sun.java.launcher = SUN_STANDARD sun.jnu.encoding = GBK sun.management.compiler = HotSpot 64-Bit Tiered Compilers sun.os.patch.level = Service Pack 1 sun.stderr.encoding = ms936 sun.stdout.encoding = ms936 user.country = CN user.dir = # pwd user.home = # ~ user.language = en user.name = Administrator user.script = user.variant =
java.util.Enumeration— legacyIterator- get
Enumeration— useCollections::enumeration,Collections::emptyEnumerationto work with legacy code
- get
java.util.Vector— legacy synchronizedArrayListjava.util.Stack— legacypublic class Stack<E> extends Vector<E>java.util.BitSet— bit vector, no perfect alternative, still in usepublic class BitSet extends Object implements Cloneable, Serializable- no boundary check — some methods (such as
size()) may overflow - creation
- constructors
valueOfcloneBitSet get(int fromIndex, int toIndex)
- no boundary check — some methods (such as
# Preferences
preferences — in
java.util.prefs- disadvantages of property files
- no uniform location
- no standard naming convention, increasing the likelihood of name clashes
- location of preferences — registry in Windows, file system for Linux, implementation hidden from user
- structure — tree structure, recommended to make the configuration node paths match the package names
- multiple users —
Preferences.userRoot(),Preferences.systemRoot()
- disadvantages of property files
java.util.prefs.Preferences—Maplikepublic abstract class Preferences extends Object- move around nodes
static Preferences userRoot()static Preferences userNodeForPackage(Class<?> c)static Preferences systemRoot()static Preferences systemNodeForPackage(Class<?> c)abstract Preferences node(String pathName)
- get value from key
abstract boolean getBoolean(String key, boolean def)abstract byte[] getByteArray(String key, byte[] def)abstract double getDouble(String key, double def)abstract float getFloat(String key, float def)abstract int getInt(String key, int def)abstract long getLong(String key, long def)
- put key-value pairs
- export and import
- more
- move around nodes
# Stream
stream
- characteristics
- no store — elements stored in an underlying collection or generated on demand, should not mutate upon terminal operation
- does not mutate source — new stream on every call
- lazy
- one-time — may throw
IllegalStateExceptionif it detects that the stream is being reused - sequential or parallel — in parallel mode when the terminal method executes, all intermediate stream operations will be parallelized, using
ForkJoinPool - ordered or not — streams that arise from ordered collections (arrays and lists), from ranges, generators, and iterators, or from calling
Stream::sortedare ordered- order and parallelism — ordering does not preclude efficient parallelism, but some operations can be more effectively parallelized without requiring order
- stream creation
- from collections and
Arrays—Collection::stream,Collection::parallelStream,Arrays::stream- under the hood —
StreamSupport::stream, which usesSpliterator
- under the hood —
- static methods in
Stream Pattern::splitAsStreamFiles::lines,BufferedReader::linesStream.BuilderRandom::ints,Random::doubles,Random::longsfor primitive variantsCharSequence::codepoints,CharSequence::chars
- from collections and
- characteristics
java.util.stream.BaseStreampublic interface BaseStream<T,S extends BaseStream<T,S>> extends AutoCloseablevoid close()boolean isParallel()Iterator <T> iterator()Spliterator <T> spliterator()S onClose(Runnable closeHandler)S parallel()S sequential()S unordered()
java.util.stream.StreamSupport— for library writers presenting stream views of data structurespublic final class StreamSupport extends Objectjava.util.stream.IntStream,java.util.stream.LongStream,java.util.stream.DoubleStreampublic interface IntStream extends BaseStream<Integer,IntStream>- methods like those in
Stream - creation — partial
range()in Pythonstatic IntStream range(int startInclusive, int endExclusive)static IntStream rangeClosed(int startInclusive, int endInclusive)static LongStream range(long startInclusive, long endExclusive)static LongStream rangeClosed(long startInclusive, long endInclusive)
- transformation
DoubleStream asDoubleStream()
LongStream asLongStream()Stream<Integer> boxed()
Stream<Double> boxed()
Stream<Long> boxed()LongSummaryStatistics summaryStatistics()
IntSummaryStatistics summaryStatistics()
DoubleSummaryStatistics summaryStatistics()
- methods like those in
java.util.stream.Streampublic interface Stream<T> extends BaseStream<T,Stream<T>>- creation
static <T> Stream<T> of(T... values)
static <T> Stream<T> of(T t)static <T> Stream<T> empty()static <T> Stream<T> generate(Supplier<T> s)— Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)— Returns an infinite sequential ordered Stream produced by iterative application of a functionfto an initial element seed, producing a Stream consisting of seed,f(seed),f(f(seed)), etc.static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)static <T> Stream.Builder<T> builder()public static interface Stream.Builder<T> extends Consumer<T>void accept(T t)
default Stream.Builder<T> add(T t)Stream<T> build()
- transformation
BaseStreammethodsStream<T> filter(Predicate<? super T> predicate)<R> Stream<R> map(Function<? super T,? extends R> mapper)
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
IntStream mapToInt(ToIntFunction<? super T> mapper)
LongStream mapToLong(ToLongFunction<? super T> mapper)<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)
IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
- query — order matters
Stream<T> limit(long maxSize)Stream<T> skip(long n)Stream<T> distinct()— usesObject::equals, the first occurrence when orderedStream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)
- reduction (terminal operation)
Optional<T> max(Comparator<? super T> comparator)Optional<T> min(Comparator<? super T> comparator)long count()Optional<T> findAny()— effective when parallelOptional<T> findFirst()boolean allMatch(Predicate<? super T> predicate)boolean anyMatch(Predicate<? super T> predicate)boolean noneMatch(Predicate<? super T> predicate)T reduce(T identity, BinaryOperator<T> accumulator)<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)Collectors::reducing
- result (terminal operation)
Stream<T> peek(Consumer<? super T> action)— consume results but an intermediate operationvoid forEach(Consumer<? super T> action)void forEachOrdered(Consumer<? super T> action)— when in parallel mode and order mattersObject[] toArray()
<A> A[] toArray(IntFunction<A[]> generator)<R,A> R collect(Collector<? super T,A,R> collector)
<R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)—CollectorshortcutList<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll); String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString();- iterator methods from
BaseStream
- creation
java.util.stream.Collector— A mutable reduction operation that accumulates input elements into a mutable result containerpublic interface Collector<T,A,R>- process
- creation of a new result container (
Supplier<A> supplier()) - incorporating a new data element into a result container (
BiConsumer<A,T> accumulator()) - combining two result containers into one (
BinaryOperator<A> combiner()) - performing an optional final transform on the container (
Function<A,R> finisher())
- creation of a new result container (
Set<Collector.Characteristics> characteristics()enum CharacteristicsCONCURRENT— Indicates that this collector is concurrent, meaning that the result container can support the accumulator function being called concurrently with the same result container from multiple threads.IDENTITY_FINISH— Indicates that the finisher function is the identity function and can be elided.Function.identity()
UNORDERED— Indicates that the collection operation does not commit to preserving the encounter order of input elements.
- creation
static <T,A,R> Collector<T,A,R> of(Supplier<A> supplier, BiConsumer<A,T> accumulator, BinaryOperator<A> combiner, Function<A,R> finisher, Collector.Characteristics... characteristics)static <T,R> Collector<T,R,R> of(Supplier<R> supplier, BiConsumer<R,T> accumulator, BinaryOperator<R> combiner, Collector.Characteristics... characteristics)- methods in
Collectors
- process
java.util.stream.Collectors- statics
static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)
static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)static <T> Collector<T,?,Optional<T>> maxBy(Comparator<? super T> comparator)static <T> Collector<T,?,Optional<T>> minBy(Comparator<? super T> comparator)static <T> Collector<T,?,DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)
static <T> Collector<T,?,IntSummaryStatistics> summarizingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T,?,LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper)static <T> Collector<T,?,Long> counting()static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)
static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)
- collector chaining
static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)— add finisherstatic <T,U,A,R> Collector<T,?,R> mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)— preprocess withT -> Ufunction for collector acceptingUgroupingBygroupingByConcurrentpartitioningBy
- group (defaults to using
HashMapandConcurrentHashMap)static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)
static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>> groupingByConcurrent(Function<? super T,? extends K> classifier)
static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>> groupingByConcurrent(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
static <T,K,A,D,M extends ConcurrentMap<K,D>> Collector<T,?,M> groupingByConcurrent(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)static <T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)
static <T,D,A> Collector<T,?,Map<Boolean,D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)
- to map (
HashMapandConcurrentHashMap)static <T,K,U> Collector<T,?,ConcurrentMap<K,U>> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
static <T,K,U,M extends ConcurrentMap<K,U>> Collector<T,?,M> toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
- to collection
static <T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)static <T> Collector<T,?,List<T>> toList()static <T> Collector<T,?,Set<T>> toSet()
- join
static Collector<CharSequence,?,String> joining()static Collector<CharSequence,?,String> joining(CharSequence delimiter)static Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
- reduce
static <T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)static <T> Collector<T,?,T> reducing(T identity, BinaryOperator<T> op)static <T,U> Collector<T,?,U> reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)
- statics
# SPI (Service Loader)
SPI
- zhihu (opens new window)
- define the interface / superclass, and provide its implementation, no hard code
- for
ServiceLoader, define inMETA-INF/services/packageName.InterfaceNameas a text file with fully qualified implementation nameimplementation.package.name.ImplName1 implementation.package.name.ImplName2 ... - example for
ServiceLoaderpublic interface Search { public List<String> searchDoc(String keyword); } // implementations and configurations omitted public class TestCase { public static ServiceLoader<Search> s = ServiceLoader.load(Search.class); public static void main(String[] args) { for (Search search : s) { search.searchDoc("hello world"); } } } java.text.spi
java.util.ServiceLoaderpublic final class ServiceLoader<S> extends Object implements Iterable<S>Iterator<S> iterator()— Lazily loads the available providers of this loader's service.static <S> ServiceLoader<S> load(Class<S> service)— Creates a new service loader for the given service type, using the current thread's context class loader.
# Other Utils
legacy date and time related — see Time
java.util.PropertyPermission— system property permissionsjava.util.UUID— an immutable universally unique identifier (UUID). A UUID represents a 128-bit value.java.util.Objects— null-safestatic <T> int compare(T a, T b, Comparator<? super T> c)—return (a == b) ? 0 : c.compare(a, b);static boolean deepEquals(Object a, Object b)— Returnstrueif the arguments are deeply equal to each other andfalseotherwise.static boolean equals(Object a, Object b)—return (a == b) || (a != null && a.equals(b));static int hash(Object... values)—return Arrays.hashCode(values);static int hashCode(Object o)—return o != null ? o.hashCode() : 0;static boolean isNull(Object obj)—return obj == null;static boolean nonNull(Object obj)—return obj != null;static <T> T requireNonNull(T obj)
static <T> T requireNonNull(T obj, String message)
static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)— Checks that the specified object reference is not null and throws a customizedNullPointerExceptionif it is.static String toString(Object o)—return String.valueOf(o);→return (obj == null) ? "null" : obj.toString();static String toString(Object o, String nullDefault)—return (o != null) ? o.toString() : nullDefault;- index check methods — since JDK 9
java.util.Optional— A container object which may or may not contain a non-null value, a betternullpublic final class Optional<T> extends Object- fallback to
nullboolean isPresent()T get()
- transformation
void ifPresent(Consumer<? super T> consumer)<U> Optional<U> map(Function<? super T,? extends U> mapper)<U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)Optional<T> filter(Predicate<? super T> predicate)T orElse(T other)T orElseGet(Supplier<? extends T> other)<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
- creation
static <T> Optional<T> empty()static <T> Optional<T> of(T value)static <T> Optional<T> ofNullable(T value)
- variants
java.util.OptionalIntjava.util.OptionalDoublejava.util.OptionalLong
- fallback to
java.util.LongSummaryStatistics,java.util.IntSummaryStatistics,java.util.DoubleSummaryStatisticspublic class LongSummaryStatistics extends Object implements LongConsumer, IntConsumer- creation
Collectors::summarizingLong,Collectors::summarizingDouble,Collectors::summarizingIntIntSummaryStatistics(long count, int min, int max, long sum)- with out collector —
IntSummaryStatistics()LongSummaryStatistics stats = longStream.collect(LongSummaryStatistics::new, LongSummaryStatistics::accept, LongSummaryStatistics::combine);
- statistics
double getAverage()long getCount()long|int|double getMax()long|int|double getMin()long|double getSum()String toString()
- creation
# ZIP, Checksum and Encryption
java.util.Base64java.util.Base64.Decoderjava.util.Base64.Encoder
java.util.zip.CRC32public class CRC32 extends Object implements Checksuminterface java.util.zip.Checksum
ZIP streams — see ZIP Streams
java.security.MessageDigest— MD5, SHA-1, SHA-256, SHA-384, and SHA-512bytesToHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(Paths.get("temp.py"))));static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length << 1]; for (int j = 0; j < bytes.length; ++j) { int v = bytes[j] & 0xFF; hexChars[j << 1] = HEX_ARRAY[v >>> 4]; hexChars[(j << 1) + 1] = HEX_ARRAY[v & 0x0F]; } return String.valueOf(hexChars); }- CLI —
keytool
- CLI —
javax.crypto.Cipher— AES, DES, RSAjava.security.KeyPairGenerator