Post

Java Cheatsheet

Array

Empty array:

1
2
int[] arr1 = new int[0];
int[][] arr2 = new int[0][0];

ArrayDeque

Null elements are prohibited.

Arrays

Collection

Collections

1
2
3
4
Integer[] arr = {1, 2, 3};
  
// Sorts arr[] in descending order 
Arrays.sort(arr, Collections.reverseOrder()); 

Comparable

Comparator

Comparator

Compare Strings by length in descending order, then by alphabetical order:

1
2
3
Comparator.comparing(String::length)
    .reversed()
    .thenComparing(Comparator.<String>naturalOrder())

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

Class Enum<E extends Enum<E>>

  • ordinal()
  • toString()
  • valueOf()

Integer

1
MAX_VALUE + 1 == MIN_VALUE

IntStream

Iterator

LinkedList

  • LinkedList Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

List

Math

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

StringBuilder

System

TreeSet

This post is licensed under CC BY 4.0 by the author.