Java Useful Methods
Java Useful Methods
1. HashMap<K, V>
Common Methods: - put(K key, V value) – Adds a key-value pair to the map. - get(Object
key) – Returns the value associated with the key. - containsKey(Object key) – Checks if the key
exists. - containsValue(Object value) – Checks if the value exists. - remove(Object key) –
Removes the entry by key. - keySet() – Returns a set of all keys. - values() – Returns a collection
of all values. - entrySet() – Returns a set of all key-value pairs. - isEmpty() – Checks if map is
empty. - size() – Returns the number of entries. - clear() – Removes all entries.
2. HashSet<E>
Common Methods: - add(E element) – Adds the element to the set. - contains(Object
element) – Checks if the set contains the element. - remove(Object element) – Removes the
element if it exists. - isEmpty() – Checks if the set is empty. - size() – Returns the number of
elements. - clear() – Removes all elements. - iterator() – Returns an iterator over elements.
3. Stack<E>
Common Methods: - push(E item) – Pushes item on top. - pop() – Removes and returns the top
item. - peek() – Returns top item without removing it. - empty() – Checks if the stack is empty. -
search(Object o) – Returns 1-based position from the top of the stack. - size() – Number of
elements.
4. ArrayList<E>
Common Methods: - add(E element) – Adds element to end. - add(int index, E element) –
Inserts element at specified position. - get(int index) – Returns element at index. - set(int
index, E element) – Replaces element at index. - remove(int index) – Removes element at
index. - remove(Object o) – Removes the first occurrence. - contains(Object o) – Checks if
element exists. - size() – Returns number of elements. - isEmpty() – Checks if list is empty. -
clear() – Removes all elements. - indexOf(Object o) – Returns first index of element. -
1
lastIndexOf(Object o) – Returns last index. - subList(int fromIndex, int toIndex) –
Returns a sub-list.
Common Methods: - add(E element) – Adds element; throws exception if full. - offer(E
element) – Adds element; returns false if fails. - remove() – Removes and returns head; throws
exception if empty. - poll() – Removes and returns head; returns null if empty. - element() –
Retrieves head; throws exception if empty. - peek() – Retrieves head; returns null if empty. -
isEmpty() – Checks if queue is empty. - size() – Number of elements.
These methods are essential for competitive programming, software engineering, and system design.
Practice them to get comfortable manipulating collections in Java.