0% found this document useful (0 votes)
18 views18 pages

Essential Java Predefined Methods Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views18 pages

Essential Java Predefined Methods Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Cheat Sheet

👋 imp predefined methods

Here’s a Java Cheat Sheet 📜with essential predefined methods that are super
useful for coding contests (CodeChef, LeetCode, etc.) and general problem-
solving. 🚀
🔥Methods
Java Cheat Sheet: Important Predefined

📌 1. Math Class (For Numerical Computations)


Method Description

Returns absolute value of x (removes negative


[Link](x)
sign).

[Link](a, b) Returns the maximum of a and b .

[Link](a, b) Returns the minimum of a and b .

[Link](x) Returns the square root of x .

[Link](a, b) Returns a^b (a raised to the power b).

Java Cheat Sheet 1


[Link](x) Rounds x up to the nearest integer.
[Link](x) Rounds x down to the nearest integer.

Rounds x to the nearest integer (normal


[Link](x)
rounding).
[Link](x) Returns natural log (ln) of x .
Math.log10(x) Returns base 10 log of x .

[Link](x) , [Link](x) , [Link](x) Returns sine, cosine, or tangent of x (radians).

[Link](deg) ,
Converts degrees ↔ radians.
[Link](rad)

[Link]() Returns a random number in [0, 1) .

Example:

java
CopyEdit
[Link]([Link](10, 20)); // 20
[Link]([Link](2, 5)); // 32.0
[Link]([Link](25)); // 5.0

📌 2. Arrays Class (For Array Operations)


Method Description
[Link](arr) Sorts the array in ascending order.
[Link](arr,
Sorts an Integer array in descending order.
[Link]())

Returns index of key in a sorted array (or -1 if not


[Link](arr, key)
found).

[Link](arr, n) Copies first n elements of arr .

[Link](arr, start, end) Copies elements from index start to end-1 .

[Link](arr, val) Fills arr with val .

[Link](arr) Converts an array to a string.

[Link](arr1, arr2) Returns true if arrays are identical.

Java Cheat Sheet 2


Example:

java
CopyEdit
import [Link];
Integer[] arr = {5, 2, 9, 1};
[Link](arr, [Link]()); // Descending order
[Link]([Link](arr)); // [9, 5, 2, 1]

📌 3. Collections Class (For Lists & Sorting)


Method Description
[Link](list) Sorts list in ascending order.
[Link](list) Reverses list .
[Link](list) Returns the maximum element.
[Link](list) Returns the minimum element.
[Link](list, x) Returns the count of x in list .
[Link](list) Randomly shuffles list .

Example:

java
CopyEdit
import [Link].*;
List<Integer> list = [Link](4, 1, 7, 9);
[Link](list);
[Link](list); // [1, 4, 7, 9]

📌 4. String Class (For String Manipulation)


Method Description

Java Cheat Sheet 3


[Link]() Returns length of s .
[Link](i) Returns character at index i .
[Link](i, j) Returns substring from i to j-1 .
[Link](x) Returns index of first occurrence of x .
[Link](x) Returns last occurrence of x .
[Link]() Converts to uppercase.
[Link]() Converts to lowercase.
[Link]() Removes leading & trailing spaces.
[Link](a, b) Replaces a with b .
[Link](" ") Splits s by spaces and returns an array.
[Link](t) Checks if s == t (case-sensitive).
[Link](t) Checks if s == t (case-insensitive).

Example:

java
CopyEdit
String s = "Hello World";
[Link]([Link](0, 5)); // "Hello"
[Link]([Link]()); // "HELLO WORLD"

📌Operations)
5. StringBuilder Class (For Efficient String

Method Description
[Link](x) Adds x at the end.
[Link](i, x) Inserts x at index i .
[Link](i, j) Deletes from index i to j-1 .
[Link]() Reverses the string.
[Link](i, x) Replaces character at i with x .

Java Cheat Sheet 4


[Link]() Converts StringBuilder to String .

Example:

java
CopyEdit
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](sb); // "Hello World"

📌 6. BufferedReader (Fast Input Handling)


Method Description
[Link]() Reads a full line as a string.
[Link]([Link]()) Converts input to integer.
[Link]().split(" ") Splits a line into tokens.

Example:

java
CopyEdit
import [Link].*;

BufferedReader br = new BufferedReader(new InputStreamReader(System.i


n));
int n = [Link]([Link]());
String[] words = [Link]().split(" ");
[Link]([Link](words));

📌 7. HashMap (For Fast Lookup)


Method Description

Java Cheat Sheet 5


[Link](k, v) Inserts key-value pair (k, v) .
[Link](k) Returns value of k , or null if not found.
[Link](k) Checks if k exists.
[Link](v) Checks if v exists.
[Link](k) Removes key k .

Example:

java
CopyEdit
HashMap<String, Integer> map = new HashMap<>();
[Link]("Alice", 25);
[Link]([Link]("Alice")); // 25

📌 8. PriorityQueue (Min & Max Heap)


Method Description
[Link](x) Inserts x .
[Link]() Removes and returns smallest (min heap).
[Link]() Returns smallest without removing.

Example (Min Heap):

java
CopyEdit
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](5);
[Link](2);
[Link](8);
[Link]([Link]()); // 2 (smallest element)

📌
Java Cheat Sheet 6
📌 9. Stack & Queue
✔ Stack (LIFO)
java
CopyEdit
Stack<Integer> stack = new Stack<>();
[Link](1);
[Link]();
[Link]();
[Link]();

✔ Queue (FIFO)
java
CopyEdit
Queue<Integer> queue = new LinkedList<>();
[Link](1);
[Link]();
[Link]();

🎯 Summary
🔹 Math: max(), min(), pow(), sqrt(), random()

🔹 Arrays: sort(), binarySearch(), toString()

🔹 Strings: substring(), split(), replace(), indexOf()

🔹 Collections: sort(), reverse(), max(), frequency()

🔹 BufferedReader: Faster Input Handling

📌 Java HashMap Cheat Sheet for DSA 🚀


Java Cheat Sheet 7
HashMap is widely used in DSA problems for fast lookups (O(1) average time
complexity). Here’s a handy cheat sheet of useful methods for competitive
programming & problem-solving.

🔹 Basic HashMap Operations


Method Description Example
put(K key, V value) Inserts key-value pair into the map. [Link](1, "A");

Returns the value associated with


get(K key) [Link](1); // Output: "A"
key (or null if key not found).
remove(K key) Removes the key-value pair. [Link](1);

[Link](1); // Output:
containsKey(K key) Checks if key exists.
true or false

containsValue(V
Checks if value exists. [Link]("A");
value)

size() Returns number of key-value pairs. [Link]();

isEmpty() Returns true if map is empty. [Link]();

🔹 Iterating Over HashMap


1️⃣ Using forEach loop

for ([Link]<Integer, String> entry : [Link]()) {


[Link]([Link]() + " -> " + [Link]());
}

2️⃣ Using forEach() method (Java 8)

[Link]((key, value) -> [Link](key + " -> " + value));

3️⃣ Iterating only Keys

Java Cheat Sheet 8


for (Integer key : [Link]()) {
[Link](key);
}

4️⃣ Iterating only Values


for (String value : [Link]()) {
[Link](value);
}

🔹 HashMap Advanced Methods


Method Description Example

getOrDefault(K key, V Returns value if key exists, [Link](5, "Not


defaultValue) otherwise returns default value. Found");

putIfAbsent(K key, V Inserts only if key is not already


[Link](1, "B");
value) present.
replace(K key, V
Updates value if key exists. [Link](1, "C");
newValue)

replace(K key, V oldValue, Updates value only if key


[Link](1, "B", "C");
V newValue) already has oldValue.

merge(K key, V value, Combines values if key exists,


[Link](1, "X", String::concat);
BiFunction) otherwise inserts.
compute(K key,
Updates value using function. [Link](1, (k, v) -> v + "!");
BiFunction)

computeIfAbsent(K key, Computes value if key does not [Link](2, k ->


Function) exist. "Generated");

computeIfPresent(K key, [Link](1, (k, v) -> v


Computes value if key exists.
BiFunction) + " Updated");

🔹 Converting HashMap to Other Data Structures


Convert to List (Keys)

Java Cheat Sheet 9


List<Integer> keys = new ArrayList<>([Link]());

Convert to List (Values)

List<String> values = new ArrayList<>([Link]());

Convert to List of Key-Value Pairs

List<[Link]<Integer, String>> entryList = new ArrayList<>([Link]


());

🔹 Common DSA Use Cases


1️⃣ Frequency Count of Elements
HashMap<Integer, Integer> freq = new HashMap<>();
int[] arr = {1, 2, 2, 3, 3, 3};

for (int num : arr) {


[Link](num, [Link](num, 0) + 1);
}

[Link](freq); // Output: {1=1, 2=2, 3=3}

2️⃣ Finding First Non-Repeating Character


String str = "leetcode";
HashMap<Character, Integer> map = new HashMap<>();

for (char c : [Link]()) {


[Link](c, [Link](c, 0) + 1);
}

Java Cheat Sheet 10


// Finding the first non-repeating character
for (char c : [Link]()) {
if ([Link](c) == 1) {
[Link](c); // Output: 'l'
break;
}
}

3️⃣ Two Sum Problem (Finding Pair with Given Sum)


int[] nums = {2, 7, 11, 15};
int target = 9;
HashMap<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < [Link]; i++) {


int complement = target - nums[i];
if ([Link](complement)) {
[Link]("Pair: " + nums[i] + ", " + complement);
break;
}
[Link](nums[i], i);
}

✔ Efficient O(N) solution using HashMap.


📌 Summary Table
Method Usage
put(key, value) Insert key-value pair
get(key) Get value of a key
remove(key) Remove key-value pair
containsKey(key) Check if key exists
containsValue(value) Check if value exists

Java Cheat Sheet 11


getOrDefault(key, defaultValue) Get value, else return default
putIfAbsent(key, value) Insert only if key is missing
replace(key, newValue) Update value if key exists
computeIfAbsent(key, function) Compute value if key is missing
computeIfPresent(key, function) Compute value if key exists

This cheat sheet covers everything you need to master HashMaps in DSA 🚀.
Let me know if you need more examples! 🔥

🔹Sheet
Java Collections Framework Cheat

1️⃣ Overview of Java Collections Framework (JCF)


The Java Collections Framework provides efficient data structures to store,
manipulate, and retrieve data.

Interface Implementation Classes Usage

Ordered, allows
List<E> ArrayList<E> , LinkedList<E>
duplicates

Unique elements, no
Set<E> HashSet<E> , LinkedHashSet<E> , TreeSet<E>
duplicates
Queue<E> PriorityQueue<E> , LinkedList<E> FIFO (First In First Out)
Deque<E> ArrayDeque<E> , LinkedList<E> Double-ended queue

HashMap<K, V> , LinkedHashMap<K, V> , Key-value pairs, unique


Map<K, V>
TreeMap<K, V> , Hashtable<K, V> keys

2️⃣ List<E> – Ordered Collection


Stores elements in order and allows duplicates.

🔹 ArrayList<E>

Java Cheat Sheet 12


✔ Dynamic array, fast random access O(1) , slow insertion/deletion O(n) .

List<Integer> list = new ArrayList<>();


[Link](10);
[Link](20);
[Link](30);
[Link](list); // [10, 20, 30]

🔹 LinkedList<E>
✔ Doubly linked list, fast insertions/deletions O(1) , slow access O(n) .

List<Integer> linkedList = new LinkedList<>();


[Link](10);
[Link](20);
[Link](30);
[Link](linkedList); // [10, 20, 30]

⚡ Common List<E> Methods

[Link](0); // Get element at index 0


[Link](1, 50); // Update index 1 to 50
[Link](); // Get size of list
[Link](2); // Remove element at index 2
[Link](10); // Check if 10 is present
[Link](20); // Get index of element 20
[Link](list); // Sort list in ascending order
[Link](list, [Link]()); // Sort in descending

3️⃣ Set<E> – Unique Collection


Stores only unique elements.

🔹 HashSet<E>

Java Cheat Sheet 13


✔ Unordered, best for searching O(1) .

Set<Integer> set = new HashSet<>();


[Link](10);
[Link](20);
[Link](10); // Duplicate ignored
[Link](set); // [10, 20]

🔹 TreeSet<E>
✔ Sorted set (ascending order), uses Red-Black Tree, O(log n) .

Set<Integer> treeSet = new TreeSet<>();


[Link](30);
[Link](10);
[Link](20);
[Link](treeSet); // [10, 20, 30]

⚡ Common Set<E> Methods

[Link](10); // Check if 10 exists


[Link](20); // Remove element 20
[Link](); // Get size of set

4️⃣ Queue<E> – FIFO Collection


✔ First In, First Out (FIFO) structure.
🔹 PriorityQueue<E>
✔ Min-Heap by default, sorts smallest element first.
Queue<Integer> pq = new PriorityQueue<>();
[Link](30);
[Link](10);

Java Cheat Sheet 14


[Link](20);
[Link]([Link]()); // Removes and prints 10 (smallest)

⚡ Common Queue<E> Methods

[Link](40); // Insert element


[Link](); // Remove and return first element
[Link](); // Return first element without removing
[Link](); // Get queue size

5️⃣ Deque<E> – Double-Ended Queue


✔ Insert & remove elements from both ends.
Deque<Integer> deque = new ArrayDeque<>();
[Link](10);
[Link](20);
[Link](5);
[Link](deque); // [5, 10, 20]

⚡ Common Deque<E> Methods

[Link](); // Remove first element


[Link](); // Remove last element
[Link](); // Get first element
[Link](); // Get last element

6️⃣ Map<K, V> – Key-Value Collection


Stores key-value pairs, keys are unique.

🔹 HashMap<K, V>
✔ Fast lookup O(1) , keys are unordered.

Java Cheat Sheet 15


Map<Integer, String> map = new HashMap<>();
[Link](1, "One");
[Link](2, "Two");
[Link](3, "Three");
[Link](map); // {1=One, 2=Two, 3=Three}

🔹 TreeMap<K, V>
✔ Sorted by keys (ascending order).
Map<Integer, String> treeMap = new TreeMap<>();
[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");
[Link](treeMap); // {1=One, 2=Two, 3=Three}

⚡ Common Map<K, V> Methods

[Link](1); // Get value by key


[Link](2); // Check if key 2 exists
[Link]("Three"); // Check if value exists
[Link](3); // Remove key 3
[Link](); // Get all keys
[Link](); // Get all values
[Link](); // Get key-value pairs

7️⃣ How to Convert Between Arrays & Lists


🔹 Convert Array → List
Integer[] arr = {10, 20, 30};
List<Integer> list = [Link](arr);

Java Cheat Sheet 16


🔹 Convert List → Array
List<Integer> list = new ArrayList<>([Link](10, 20, 30));
Integer[] arr = [Link](new Integer[0]);

8️⃣ Wrapper Classes & valueOf()


✔ Wrapper classes ( , , , etc.) are object representations of
Integer Double Character

primitive data types.


✔ converts a String → Wrapper Object.
valueOf()

Integer num = [Link]("100"); // Converts String "100" to Integer


Double d = [Link]("12.34"); // Converts String to Double

🚀 Best Practices for Coding Interviews


✅ Use ArrayList for fast access, LinkedList for frequent insertions/deletions.
✅ Use HashMap for quick key-value lookups.

✅ Use PriorityQueue for finding smallest/largest elements efficiently.


✅ Use TreeSet / TreeMap for sorted order retrieval.

💡 TL;DR (Too Long; Didn’t Read)


✔ List<E> (ArrayList, LinkedList) → Ordered, duplicates allowed.
✔ Set<E> (HashSet, TreeSet) → Unique elements only.
✔ Queue<E> (PriorityQueue) → FIFO, sorted elements.
✔ Deque<E> (ArrayDeque) → Insert/remove from both ends.

✔ Map<K, V> (HashMap, TreeMap) → Key-value storage.


✔ [Link]() → Sorting.
✔ [Link]() & [Link]() → Convert between Arrays & Lists.

Let me know if you need any clarifications! 🚀🔥


Java Cheat Sheet 17
Java Cheat Sheet 18

You might also like