Skip to content

Latest commit

 

History

History
336 lines (267 loc) · 37.1 KB

java.md

File metadata and controls

336 lines (267 loc) · 37.1 KB

Table of contents

General Data Structure

Arrays

Operation Code Description TC
One Dimensional
int[] myArr = new int[10];
Creates a one-dimensional array of integers with a length of 10.
Two dimensional
int[][] myArr = new int[10][20];
Creates a two-dimensional array of integers with dimensions 10x20.
Array literals
int[] myArr = new int[]{1, 2, 3};
int[] myArr = {1, 2, 3};
int[][] myArr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Initializes arrays with literal values.
Accessing
for (int i = 0; i < myArr.length; i++) { System.out.print(myArr[i]); }
for (int[] row : myArr) { for (int element : row) { System.out.print(element); } }
Iterates through elements of the array using loops.

Strings

Operation Code Description TC
Creation
String test = new String("ok");
Creates a new String object using the constructor.
String Literal
String test = "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 (char c : chArr) { System.out.print(c); }
for (int i = 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
import java.util.HashMap;
Importing the required HashMap class.
Creation (diff types)
HashMap<String, String> hm = new HashMap<>();
Creates a new HashMap object.
Add Element
hm.put("gopha", "ok");
Adds an element to the HashMap with the specified key and value. O(1)
Update Element
hm.put("gopha", hm.getOrDefault("gopha", "newvalue"));
Attempts to retrieve the value for the key "gopha". If not present, "newvalue" will be used instead and saved for the respective key of "gopha". O(1)
Remove element
hm.remove("gopha");
Removes the entry with the specified key from the HashMap. O(1)
Search Element
hm.containsKey("gopha");
hm.containsValue("ok");
Checks if the HashMap contains the specified key or value. O(1)
Size
hm.size();
Returns the number of key-value mappings in this HashMap.
Accessing
for (Map.Entry<String, String> entry : hm.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); }
for (String key : hm.keySet()) { System.out.println(key); }
for (String value : hm.values()) { System.out.println(value); }
Accesses the elements of the HashMap using various methods such as iterating over entries, keys, or values.
computeIfAbsent
hm.computeIfAbsent("key", k -> "defaultValue");
Computes the value if absent and returns the computed value associated with the key. O(1)
computeIfAbsent with List
import java.util.ArrayList;HashMap<String, List<String>> hm = new HashMap<>();hm.computeIfAbsent("key", k -> new ArrayList<>()).add("value");
Computes the list value if absent, returns the list associated with the key, and adds an element to the list. O(1)

LinkedHashMap

A HashMap that maintains the order of insertion.

Operation Code Description TC
Import required
import java.util.LinkedHashMap;
Importing the required LinkedHashMap class.
Creation
LinkedHashMap<String, String> lhm = new LinkedHashMap<>();
Creates a new LinkedHashMap object.
Add Element
lhm.put("gopha", "ok");
Adds an element to the LinkedHashMap with the specified key and value. O(1)
Update Element
lhm.put("gopha", lhm.getOrDefault("gopha", "newvalue"));
Attempts to retrieve the value for the key "gopha". If not present, "newvalue" will be used instead and saved for the respective key of "gopha". O(1)
Remove Element
lhm.remove("gopha");
Removes the entry with the specified key from the LinkedHashMap. O(1)
Search Element
lhm.containsKey("gopha");
lhm.containsValue("ok");
Checks if the LinkedHashMap contains the specified key or value. O(1)
Size
lhm.size();
Returns the number of key-value mappings in this LinkedHashMap.
Accessing
for (Map.Entry<String, String> entry : lhm.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); }
for (String key : lhm.keySet()) { System.out.println(key); }
for (String value : 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
import java.util.ArrayList;LinkedHashMap<String, List<String>> lhm = new LinkedHashMap<>();lhm.computeIfAbsent("key", k -> new ArrayList<>()).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.

Operation Code Description TC
Import required
import java.util.TreeMap;
Importing the required TreeMap class.
Creation
TreeMap<Integer, String> treeMap = new TreeMap<>();
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
import java.util.HashSet;
Importing the required HashSet class.
Creation
HashSet hs = new HashSet<>();
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 (String s : 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
import java.util.ArrayList;
Importing the required ArrayList class.
Creation
ArrayList list = new ArrayList<>();

List list = new ArrayList<>();
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
List temp = new ArrayList<>();
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 (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
for (String s : list) { System.out.println(s); }
Iterates through the elements of the list using both traditional and enhanced for loop. O(n)
Sorting
import java.util.Collections;
Collections.sort(list);
Collections.sort(list, Collections.reverseOrder());
Sorts the elements of the list in ascending or descending order. O(n log n)
Convert to Array of Non-Primitive Data Type
T[] arr = list.toArray(new T[0]);
Converts the list to an array. O(n)
Convert to Array of Primitive Data Type
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Converts the list to primitive array. O(n)

LinkedList

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
import java.util.LinkedList;
Importing the required LinkedList class.
Creation
LinkedList list = new LinkedList<>();
LinkedList ll = new LinkedList(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 (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
for (int i : 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.

Operation Code Description TC
Import required
import java.util.PriorityQueue;
Importing the required PriorityQueue class.
Creation (Min-Heap)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
Creates a PriorityQueue with default natural ordering. O(1)
Creation (Max-Heap)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
Creates a PriorityQueue with reverse order for max heap. O(1)
Creation (Custom Comparator)
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue().equals(b.getValue()) ? a.getKey().compareTo(b.getKey()) : a.getValue() - b.getValue());
Creates a PriorityQueue with a custom comparator using a lambda expression. O(1)
Custom Comparator with Lambda
import java.util.PriorityQueue;import java.util.Comparator;import java.util.Map;public class Main {    public static void main(String[] args) {        PriorityQueue<Integer> pq = new PriorityQueue<>(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 (Integer element : 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
import java.util.Queue;

import java.util.LinkedList;
Importing the required Queue interface and LinkedList class.
Creation
Queue<Integer> q = new LinkedList<>();
Creates a new Queue instance using LinkedList.
Add Element
q.add(10);

boolean success = 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 (Integer element : 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
import java.util.Deque;

import java.util.LinkedList;
Importing the required Deque interface and LinkedList class.
Creation
Deque<Integer> deque = new LinkedList<>();
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 (Integer element : 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
import java.util.Stack;
Importing the required Stack class.
Creation
Stack<Integer> st = new Stack<>();
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 (Integer element : 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
StringBuilder sb = new StringBuilder();
StringBuffer sbf = new StringBuffer();
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
import javafx.util.Pair;
Importing the required Pair class.
Pair Class
Pair<Integer, String> pair = new Pair<>(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. int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(arr);
Arrays.asList(T... arr) Returns a fixed-size list backed by the specified array. String[] arr = {"apple", "banana", "cherry"};
List<String> list = Arrays.asList(arr);
Arrays.fill(T[] arr, T val) Assigns the specified value to each element of the specified array. int[] arr = new int[5];
Arrays.fill(arr, 7);
Arrays.equals(T[] arr1, T[] arr2) Returns true if the two specified arrays of objects are equal to one another. int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean isEqual = Arrays.equals(arr1, arr2);
Arrays.copyOf(T[] original, int newLength) Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. int[] arr = {1, 2, 3};
int[] newArr = Arrays.copyOf(arr, 5);
Arrays.toString(T[] arr) Returns a string representation of the contents of the specified array. int[] arr = {1, 2, 3};
String str = Arrays.toString(arr);

Character Utils

Method Signature Description Example
Character.isLetter(char ch) Determines if the specified character is a letter. char ch = 'A';
boolean isLetter = Character.isLetter(ch);
Character.isDigit(char ch) Determines if the specified character is a digit. char ch = '5';
boolean isDigit = Character.isDigit(ch);
Character.isWhitespace(char ch) Determines if the specified character is white space. char ch = ' ';
boolean isWhitespace = Character.isWhitespace(ch);
Character.isUpperCase(char ch) Determines if the specified character is an uppercase letter. char ch = 'A';
boolean isUpperCase = Character.isUpperCase(ch);
Character.isLowerCase(char ch) Determines if the specified character is a lowercase letter. char ch = 'a';
boolean isLowerCase = Character.isLowerCase(ch);
Character.isLetterOrDigit(char ch) Determines if the specified character is a letter or digit. char ch = '7';
boolean isLetterOrDigit = Character.isLetterOrDigit(ch);
Character.toUpperCase(char ch) Converts the specified character to uppercase. char ch = 'a';
char upperCaseCh = Character.toUpperCase(ch);
Character.toLowerCase(char ch) Converts the specified character to lowercase. char ch = 'A';
char lowerCaseCh = Character.toLowerCase(ch);
Character.compare(char x, char y) Compares two char values numerically. char x = 'A';
char y = 'B';
int result = Character.compare(x, y);
Character.digit(char ch, int radix) Returns the numeric value of the specified character (for radix up to 36). Returns -1 if the character is not a digit. char ch = '7';
int digitValue = Character.digit(ch, 10);

Integer Utils

Method Signature Description Example
Integer.parseInt(String s) Parses the string argument as a signed decimal integer. String str = "123";
int num = Integer.parseInt(str);
Integer.valueOf(int i) Returns an Integer instance representing the specified int value. int num = 123;
Integer integer = Integer.valueOf(num);

Collection Utils

Method Signature Description Example
Collections.sort(List<T> list) Sorts the specified list into ascending order, according to the natural ordering of its elements. List<Integer> numbers = Arrays.asList(3, 1, 2);
Collections.sort(numbers);
Collections.sort(List<T> list, Comparator<? super T> c) Sorts the specified list according to the order induced by the specified comparator. List<String> strings = Arrays.asList("banana", "apple", "orange");
Collections.sort(strings, Comparator.reverseOrder());

Comparator Class

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.

Operation Code Description TC
Import required
import java.util.Comparator;
Importing the required Comparator interface.
Comparator with Lambda
Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length();
Creates a comparator using a lambda expression to compare strings by length. O(1)
Comparator with Method Reference
Comparator<String> comparator = Comparator.comparingInt(String::length);
Creates a comparator using a method reference to compare strings by length. O(1)