Java Cheatsheet
Array
Empty array:
1
2
int[] arr1 = new int[0];
int[][] arr2 = new int[0][0];
ArrayDeque
Null elements are prohibited.
Arrays
- public static <T> List<T> asList(T… a): fixed-size, mutable
- public static <T> int compare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)
- public static <T> T[] copyOf(T[] original, int newLength)
- public static boolean equals(Object[] a, Objecti[] a2)
- public static void fill(Object[] a, int fromIndex, int toIndex, Object val): Assigns the specified Object reference to each element
- static <E> List<E> of(E… elements): immutable
- public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c): stable
- public static String toString(Object[] a)
Collection
Collections
- public static boolean disjoint(Collection<?> c1, Collection<?> c2)
- public static final <T> List<T> emptyList(): immutable
- public static <T> void fill(List<? super T> list, T obj)
- public static int frequency(Collection<?> c, Object o)
- public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
- public static <T> List<T> nCopies(int n, T o): immutable
- public static void reverse(List<?> list)
- public static <T> Comparator<T> reverseOrder()
1
2
3
4
Integer[] arr = {1, 2, 3};
// Sorts arr[] in descending order
Arrays.sort(arr, Collections.reverseOrder());
- public static <T> void sort(List<T> list, Comparator<? super T> c): stable
- public static void swap(List<?> list, int i, int j)
Comparable
Comparator
Compare Strings by length in descending order, then by alphabetical order:
1
2
3
Comparator.comparing(String::length)
.reversed()
.thenComparing(Comparator.<String>naturalOrder())
- static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
- static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
- default Comparator<T> reversed()
- static <T extends Comparable<? super T>> Comparator<T> reverseOrder()
Comparator.reverseOrder()
is preferable over Collections.reverseOrder()
because it enforces the type argument to be a subtype of Comparable
, and thus type safe.
Decimal
https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/text/DecimalFormat.html
1
2
DecimalFormat df = new DecimalFormat("0.00");
df.format("1.2345"); // "1.23"
Deque
Deque Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack
class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque.
1
Deque<Integer> stack = new ArrayDeque<>();
Enum
- ordinal()
- toString()
- valueOf()
Integer
- MAX_VALUE: 2^31-1 = 2147483647 ~= 2e9 (10 digits)
- MIN_VALUE: -2^31 = -2147483648 ~= -2e9 (10 digits)
- public static int bitCount(int i)
- public int intValue()
- public static int highestOneBit(int i)
- public static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix) throws NumberFormatException
- public static String toBinaryString(int i)
- public static String toString(int i,int radix)
1
MAX_VALUE + 1 == MIN_VALUE
IntStream
Iterator
LinkedList
- LinkedList Doubly-linked list implementation of the
List
andDeque
interfaces. Implements all optional list operations, and permits all elements (includingnull
).
List
Math
- public static double random(): it internally uses
Random.nextDouble()
1
2
// number of digits in n
int k = (int) (Math.log10(n) + 1);
Object
Priority Queue
The Iterator provided in method iterator()
and the Spliterator provided in method spliterator()
are not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
Scanner
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Scanner.html
Fraction Addition and Subtraction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public String fractionAddition(String expression) {
Scanner sc = new Scanner(expression).useDelimiter("/|(?=[-+])");
int num = 0, den = 1;
while (sc.hasNext()) {
int a = sc.nextInt(), b = sc.nextInt();
num = num * b + a * den;
den *= b;
int g = gcd(num, den);
num /= g;
den /= g;
}
return num + "/" + den;
}
private int gcd(int a, int b) {
a = Math.abs(a);
while (b != 0) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
Set
Stream
String
- public String(char[] value, int offset, int count)
- public boolean contains(CharSequence s)
- public int indexOf(String str, int fromIndex)
- public static String join(CharSequence delimiter, CharSequence… elements)
- public int lastIndexOf(int ch, int fromIndex): searching backward starting at the specified index.
- public String repeat(int count)
- public String replace(char oldChar, char newChar)
- public String replaceAll(String regex, String replacement)
- public boolean startsWith(String prefix, int toffset)
- public String strip()
- public String stripLeading()
- substring(int beginIndex):
0 <= beginIndex <= s.length()
- substring(int beginIndex, int endIndex):
0 <= beginIndex <= endIndex <= s.length()
StringBuilder
- public StringBuilder delete(int start, int end)
- public StringBuilder deleteCharAt(int index)
- public StringBuilder replace(int start, int end, String str)
- public StringBuilder reverse()
- public void setLength(int newLength)