You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
for (inti = 0; i < myArr.length; i++) { System.out.print(myArr[i]); }
for (int[] row : myArr) { for (intelement : row) { System.out.print(element); } }
Iterates through elements of the array using loops.
Strings
Operation
Code
Description
TC
Creation
Stringtest = newString("ok");
Creates a new String object using the constructor.
String Literal
Stringtest = "ok";
Creates a String object using string literal, which is more efficient and recommended.
Size
test.length();
Returns the length of the string.
Accessing
char[] chArr = test.toCharArray();
for (charc : chArr) { System.out.print(c); }
for (inti = 0; i < test.length(); i++) { System.out.print(test.charAt(i)); }
Converts the string to a character array and iterates through each character using both enhanced for loop and traditional for loop.
charAt
test.charAt(index);
Returns the character at the specified index in the string.
O(1)
compareTo
test.compareTo("anotherString");
Compares two strings lexicographically. Returns a negative integer, zero, or a positive integer as the string is less than, equal to, or greater than the specified string.
contains
test.contains("substring");
Checks if the string contains the specified substring.
indexOf
test.indexOf("substring");
Returns the index of the first occurrence of the specified substring within the string, or -1 if not found.
substring
test.substring(startIndex, endIndex);
Returns a substring of the string starting from the specified startIndex (inclusive) to the endIndex (exclusive).
startsWith
test.startsWith("prefix");
Checks if the string starts with the specified prefix.
endsWith
test.endsWith("suffix");
Checks if the string ends with the specified suffix.
toUpperCase
test.toUpperCase();
Returns a new string with all characters converted to uppercase.
toLowerCase
test.toLowerCase();
Returns a new string with all characters converted to lowercase.
trim
test.trim();
Returns a new string with leading and trailing whitespace removed.
split
String[] parts = test.split("regex");
Splits the string into an array of substrings based on the specified regular expression.
Map
HashMap
A data structure that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.
Operation
Code
Description
TC
Import required
importjava.util.HashMap;
Importing the required HashMap class.
Creation (diff types)
HashMap<String, String> hm = newHashMap<>();
Creates a new HashMap object.
Add Element
hm.put("gopha", "ok");
Adds an element to the HashMap with the specified key and value.
for (Stringkey : lhm.keySet()) { System.out.println(key); }
for (Stringvalue : lhm.values()) { System.out.println(value); }
Accesses the elements of the LinkedHashMap using various methods such as iterating over entries, keys, or values.
computeIfAbsent
lhm.computeIfAbsent("key", k -> "defaultValue");
Computes the value if absent and returns the computed value associated with the key.
O(1)
computeIfAbsent with List
importjava.util.ArrayList;LinkedHashMap<String, List<String>> lhm = newLinkedHashMap<>();lhm.computeIfAbsent("key", k -> newArrayList<>()).add("value");
Computes the list value if absent, returns the list associated with the key, and adds an element to the list.
O(1)
TreeMap
A Red-Black tree-based NavigableMap implementation. It is sorted according to the natural ordering of its keys, or by a Comparator provided at the time of creation.
Creates a new TreeMap object with keys sorted in natural order.
Add Element
treeMap.put(1, "apple");
Adds an element to the TreeMap with the specified key and value.
O(log n)
Remove element
treeMap.remove(1);
Removes the entry with the specified key from the TreeMap.
O(log n)
Search Element
treeMap.containsKey(1);
treeMap.containsValue("apple");
Checks if the TreeMap contains the specified key or value.
O(log n)
Size
treeMap.size();
Returns the number of key-value mappings in this TreeMap.
O(1)
Accessing
treeMap.get(1);
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
O(log n)
Navigable Operations
treeMap.firstEntry();
treeMap.lastEntry();
treeMap.ceilingEntry(5);
treeMap.floorEntry(5);
Provides navigational operations for retrieval based on keys.
O(log n)
Comparison
Aspect
HashMap
LinkedHashMap
TreeMap
Order
No order
Insertion order
Sorted order
Performance
O(1) average for add, remove, search
O(1) average for add, remove, search
O(log n) for add, remove, search
Use Case
Fast access without concern for order
Maintain insertion order
Maintain natural ordering of keys
Structure
Hash table
Hash table with linked list of entries
Red-Black tree
HashSet
A collection that uses a Hash table for storage, only allowing unique elements to be added.
Operation
Code
Description
TC
Import required
importjava.util.HashSet;
Importing the required HashSet class.
Creation
HashSeths = newHashSet<>();
Creates a new HashSet object.
Add Element
hs.add("gopha ok");
Adds an element to the HashSet.
O(1)
Remove Element
hs.remove("gopha ok");
Removes the specified element from the HashSet.
O(1)
Search element
hs.contains("gopha ok");
Checks if the HashSet contains the specified element.
O(1)
Size
hs.size();
Returns the number of elements in the HashSet.
O(1)
Accessing
for (Strings : hs) { System.out.println(s); }
Iterates through the elements of the HashSet.
ArrayList
A collection of data elements sequentially ordered from 0 to length - 1. This means that we are able to access an element inside an ArrayList by its position (index).
Operation
Code
Description
TC
Import required
importjava.util.ArrayList;
Importing the required ArrayList class.
Creation
ArrayListlist = newArrayList<>();
Listlist = newArrayList<>();
Creates a new ArrayList object.
Add Element
list.add(1);
Adds an element to the end of the list.
O(1)
Add Element at Start
list.add(0, yourObject);
Inserts the specified element at the specified position in this list.
O(n)
Update Element
list.set(0, 100);
Updates the element at the specified index with the given value.
O(1)
Remove Element
list.remove(0);
list.clear();
Removes the element at the specified index or removes all elements from the list.
O(n)
Remove Last Element in List
Listtemp = newArrayList<>();
index=temp.size()-1; temp.remove(index);
Removes the last element from the list.
O(1)
Size
list.size();
Returns the number of elements in the list.
O(1)
Accessing
for (inti = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
for (Strings : list) { System.out.println(s); }
Iterates through the elements of the list using both traditional and enhanced for loop.
A linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence.
Operation
Code
Description
TC
Import required
importjava.util.LinkedList;
Importing the required LinkedList class.
Creation
LinkedListlist = newLinkedList<>();
LinkedListll = newLinkedList(C);
Creates a new LinkedList instance, either empty or containing elements from a specified collection.
Insert Element
list.add(1);
Inserts an element at the end of the linked list.
O(1)
Update Element
list.set(0, 100);
Updates the element at the specified index with the given value.
O(1)
Remove Element
list.remove(0);
list.remove(1);
list.clear();
Removes elements from the linked list: by index, by element, or all elements.
O(1)
Size
list.size();
Returns the number of elements in the linked list.
O(1)
Accessing
for (inti = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
for (inti : list) { System.out.println(s); }
Accesses elements of the linked list using a loop.
O(n)
Get Last Element
list.getLast();
Returns the last element in the linked list.
O(1)
Get First Element
list.getFirst();
Returns the first element in the linked list.
O(1)
Heap
A specialized tree-based data structure that satisfies the heap property: if A is a parent node of B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap. A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater than or equal to those of the children, and the highest key is in the root node. In a min heap, the keys of parent nodes are less than or equal to those of the children, and the lowest key is in the root node.
Creates a PriorityQueue with a custom comparator using a lambda expression.
O(1)
Custom Comparator with Lambda
importjava.util.PriorityQueue;importjava.util.Comparator;importjava.util.Map;publicclassMain { publicstaticvoidmain(String[] args) { PriorityQueue<Integer> pq = newPriorityQueue<>(Comparator.comparingInt(Math::abs)); // Add elements pq.add(-5); pq.add(3); pq.add(-2); pq.add(1); // Remove and print elements while (!pq.isEmpty()) { System.out.println(pq.poll()); } }}
Orders elements based on their absolute values using a lambda expression and Comparator.comparingInt.
Add Element
pq.add(10);
Adds an element to the priority queue.
O(log n)
View Top Element
pq.peek();
Returns but does not remove the top element from the priority queue.
O(1)
Remove Element
pq.poll();
Returns and removes the top element from the priority queue.
O(log n)
Size
pq.size();
Returns the number of elements in the priority queue.
O(1)
Accessing
for (Integerelement : pq) { System.out.println(element); }
Iterates through the elements of the priority queue (not in heap order).
O(n)
Queue
A collection of elements, supporting two principal operations: enqueue, which inserts an element into the queue, and dequeue, which removes an element from the queue.
Operation
Code
Description
TC
Import required
importjava.util.Queue;
importjava.util.LinkedList;
Importing the required Queue interface and LinkedList class.
Creation
Queue<Integer> q = newLinkedList<>();
Creates a new Queue instance using LinkedList.
Add Element
q.add(10);
booleansuccess = q.offer(10);
Adds an element to the queue using add(), which throws an exception if the queue is full, or offer(), which returns false if the queue is full.
O(1)
View Top Element
q.peek();
Returns the head of the queue, or null if the queue is empty.
O(1)
Remove Element
q.poll();
Removes and returns the head of the queue, or null if the queue is empty.
O(1)
Size
q.size();
Returns the number of elements in the queue.
O(1)
Is Empty
q.isEmpty();
Returns true if the queue is empty.
O(1)
Accessing
for (Integerelement : q) { System.out.println(element); }
Iterates through the elements of the queue.
O(n)
Dequeue
A double-ended queue (pronounced "deck") that supports insertion and removal of elements from both ends.
Operation
Code
Description
TC
Import required
importjava.util.Deque;
importjava.util.LinkedList;
Importing the required Deque interface and LinkedList class.
Creation
Deque<Integer> deque = newLinkedList<>();
Creates a new Deque instance using LinkedList.
Add Element at Front
deque.addFirst(10);
Inserts the specified element at the front of the deque.
O(1)
Add Element at End
deque.addLast(20);
Inserts the specified element at the end of the deque.
O(1)
View First Element
deque.peekFirst();
Retrieves, but does not remove, the first element of the deque, or returns null if the deque is empty.
O(1)
View Last Element
deque.peekLast();
Retrieves, but does not remove, the last element of the deque, or returns null if the deque is empty.
O(1)
Remove First Element
deque.pollFirst();
Retrieves and removes the first element of the deque, or returns null if the deque is empty.
O(1)
Remove Last Element
deque.pollLast();
Retrieves and removes the last element of the deque, or returns null if the deque is empty.
O(1)
Size
deque.size();
deque.isEmpty();
Returns the number of elements in the deque. Returns true if the deque is empty.
O(1)
Accessing
for (Integerelement : deque) { System.out.println(element); }
Iterates through the elements of the deque.
O(n)
Stack
A collection of elements, with two principal operations: push, which adds to the collection, and pop, which removes the most recently added element.
Operation
Code
Description
TC
Import required
importjava.util.Stack;
Importing the required Stack class.
Creation
Stack<Integer> st = newStack<>();
Creates a new Stack object.
Insert Element
st.push(10);
Inserts an element onto the top of the stack.
O(1)
View Top Element
st.peek();
Returns the top element of the stack without removing it.
O(1)
Remove Element
st.pop();
Removes the top element from the stack and returns it.
O(1)
Size
st.size();
st.isEmpty();
Returns the number of elements in the stack. Returns true if the stack is empty.
O(1)
Accessing
for (Integerelement : st) { System.out.println(element); }
Iterates through the elements of the stack.
O(n)
StringBuilder && StringBuffer
Comparison
Aspect
StringBuilder
StringBuffer
Mutability
Mutable
Mutable
Thread Safety
Not thread-safe
Thread-safe
Performance
Typically faster
Slightly slower due to synchronization
Usability
Preferred in single-threaded environments
Preferred in multithreaded environments
Introduced in
Java 5
Early versions of Java
Compatibility
Part of Java Collections Framework
Available for compatibility reasons
Methods
Identical methods and behavior
Identical methods and behavior
Operations
Operation
Code
Description
TC
Creation
StringBuildersb = newStringBuilder();
StringBuffersbf = newStringBuffer();
Creates a new instance of StringBuilder and StringBuffer respectively.
Append
sb.append("hello");
sbf.append("world");
Appends the specified string representation to the end of the sequence.
O(1)
Insert
sb.insert(0, "java");
sbf.insert(0, "hello");
Inserts the specified string representation at the specified position.
O(n)
Replace
sb.replace(0, 2, "hi");
sbf.replace(0, 2, "hi");
Replaces the characters in a substring of the sequence with characters in the specified string.
O(n)
Delete
sb.delete(0, 2);
sbf.delete(0, 2);
Removes the characters in a substring of this sequence.
O(n)
Reverse
sb.reverse();
sbf.reverse();
Causes this character sequence to be replaced by the reverse of the sequence.
O(n)
Get Length
sb.length();
sbf.length();
Returns the length (number of characters) of the character sequence.
O(1)
Set Length
sb.setLength(5);
sbf.setLength(5);
Sets the length of the character sequence. If the new length is greater than the current length, null characters ('\u0000') are appended to reach the specified length. If the new length is less than the current length, the sequence is truncated.
O(n)
Convert to String
sb.toString();
sbf.toString();
Returns a string representing the data in the sequence.
O(n)
Pair Class
Operation
Code
Description
TC
Import required
importjavafx.util.Pair;
Importing the required Pair class.
Pair Class
Pair<Integer, String> pair = newPair<>(1, "one");
Represents a generic pair of two objects.
Get First Item
pair.getKey();
Returns the first item of the pair.
O(1)
Get Second Item
pair.getValue();
Returns the second item of the pair.
O(1)
Math Utils
Method Signature
Description
Example
Math.max(int a, int b)
Returns the maximum of two integers.
int result = Math.max(5, 8);
Math.min(int a, int b)
Returns the minimum of two integers.
int result = Math.min(5, 8);
Math.abs(int x)
Returns the absolute value of an integer.
int result = Math.abs(-5);
Math.pow(double a, double b)
Returns the value of the first argument raised to the power of the second argument.
double result = Math.pow(2, 3);
Math.sqrt(double x)
Returns the positive square root of a double value.
double result = Math.sqrt(25);
Math.ceil(double a)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
double result = Math.ceil(4.3);
Math.floor(double a)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
double result = Math.floor(4.9);
Math.round(float a)
Returns the closest integer to the argument, with ties rounding to positive infinity.
long result = Math.round(4.5);
Math.random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
double result = Math.random();
Arrays Utils
Method Signature
Description
Example
Arrays.sort(T[] arr)
Sorts the specified array of objects into ascending order.
Comparators are used to define custom orderings for collections. They provide an ordering for collections of objects that don’t have a natural ordering, or if you want a different ordering.