Table of Contents
Open Table of Contents
Data Structures
Array
int[] arr = new int[10]; // Initialize an array
int[] arr = new int[]{1, 2, 3, 4, 5}; // Initialize an array with values
int len = arr.length; // Get the length of an array
int[] copy = Arrays.copyOf(arr, arr.length); // Copy an array
int[] copy = Arrays.copyOfRange(arr, 1, 3); // Copy a range of an array
Arrays.sort(arr); // Sort an array
Arrays.fill(arr, 0); // Fill an array with a specific value
Queue
Queue<Integer> queue = new LinkedList<>();
queue.offer(1); // Add an element to the queue
queue.poll(); // Remove and return the head of the queue
queue.peek(); // Return the head of the queue
queue.size(); // Get the size of the queue
queue.isEmpty(); // Check if the queue is empty
Stack
Stack<Integer> stack = new Stack<>();
stack.push(1); // Push an element to the stack
stack.pop(); // Pop and return the top of the stack
stack.peek(); // Return the top of the stack
stack.size(); // Get the size of the stack
stack.isEmpty(); // Check if the stack is empty
Set
Set<Integer> set = new HashSet<>();
set.add(1); // Add an element to a set
set.contains(1); // Check if an element exists in a set
set.remove(1); // Remove an element from a set
set.size(); // Get the size of a set
set.clear(); // Clear all elements in a set
Map
Map<Integer, String> map = new HashMap<>();
map.put(1, "One"); // Put a key-value pair to a map
map.get(1); // Get the value by key
map.containsKey(1); // Check if a key exists in a map
map.containsValue("One"); // Check if a value exists in a map
map.remove(1); // Remove a key-value pair from a map
map.size(); // Get the size of a map
map.clear(); // Clear all key-value pairs in a map
Priority Queue / Heap
PriorityQueue<Integer> pq = new PriorityQueue<>(); // Create a min heap
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // Create a max heap
PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(1, 2, 3)); // Initialize a priority queue with values
pq.offer(1); // Add an element to the priority queue
pq.poll(); // Remove and return the head of the priority queue
pq.peek(); // Return the head of the priority queue
pq.size(); // Get the size of the priority queue
pq.isEmpty(); // Check if the priority queue is empty
// Custom comparator
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); // Create a max heap
Classes
String
String str = "Hello, World!";
int len = str.length(); // Get the length of a string
char ch = str.charAt(0); // Get the character at index 0
String sub = str.substring(0, 5); // Get the substring from index 0 to 4
String[] parts = str.split(","); // Split a string by ","
String newStr = str.replace("Hello", "Hi"); // Replace "Hello" with "Hi"
String lower = str.toLowerCase(); // Convert the string to lowercase
String upper = str.toUpperCase(); // Convert the string to uppercase
// Join strings
String.join(",", "a", "b", "c"); // "a,b,c"
String.join(",", Arrays.asList("a", "b", "c")); // "a,b,c"