0% found this document useful (0 votes)
13 views

ArrayList

The document provides a comprehensive overview of various inbuilt functions in Java, including ArrayList, LinkedList, Stack, Queue, String, Map, Set, and Array. Each section details methods for adding, accessing, modifying, removing, and iterating through elements, along with utility functions for size checking and conversion. It serves as a reference guide for developers to understand and utilize these data structures effectively.

Uploaded by

Krishika
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

ArrayList

The document provides a comprehensive overview of various inbuilt functions in Java, including ArrayList, LinkedList, Stack, Queue, String, Map, Set, and Array. Each section details methods for adding, accessing, modifying, removing, and iterating through elements, along with utility functions for size checking and conversion. It serves as a reference guide for developers to understand and utilize these data structures effectively.

Uploaded by

Krishika
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

INBUILT FUNCTIONS

SNO TOPIC PAGE NO


1 ArrayList 1

2 LinkedList 3

3 Stack 6

4 Queue 8

5 String 9

6 Map 13

7 Set 19

8 Array 24
ArrayList<String> list = new ArrayList<>();
1. Adding Elements
 add(E e): Appends the specified element to the end of the list.
list.add("Element");
 add(int index, E element): Inserts the specified element at the specified position.
list.add(1, "Element");

2. Accessing Elements
 get(int index): Returns the element at the specified position.
String element = list.get(0);

3. Modifying Elements
 set(int index, E element): Replaces the element at the specified position with the specified
element.
list.set(1, "NewElement");

4. Removing Elements
 remove(int index): Removes the element at the specified position.
list.remove(0);
 remove(Object o): Removes the first occurrence of the specified element.
list.remove("Element");
 clear(): Removes all elements from the list.
list.clear();

5. Checking Size
 size(): Returns the number of elements in the list.
int size = list.size();

6. Searching for Elements


 contains(Object o): Returns true if the list contains the specified element.
boolean exists = list.contains("Element");
 indexOf(Object o): Returns the index of the first occurrence of the specified element, or -1 if not
found.
int index = list.indexOf("Element");
 lastIndexOf(Object o): Returns the index of the last occurrence of the specified element.
int lastIndex = list.lastIndexOf("Element");

7. Iterating Through the List


 iterator(): Returns an iterator over the elements.
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

8. Converting to Array
 toArray(): Converts the list to an array.
Object[] array = list.toArray();
 toArray(T[] a): Converts the list to an array of the specified type.
String[] array = list.toArray(new String[0]);

9. Sublist and Other Utilities


 subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified
indices.
List<String> sublist = list.subList(1, 3);
 isEmpty(): Checks if the list is empty.
boolean empty = list.isEmpty();

10. Sorting and Reversing


 sort(Comparator<? super E> c): Sorts the list using the provided comparator.
list.sort(String::compareTo);
 Collections.reverse(List<E> list): Reverses the list.
Collections.reverse(list);
LinkedList<String> list = new LinkedList<>();
1. Adding Elements
 add(E e): Appends the specified element to the end of the list.
list.add("Element");
 add(int index, E element): Inserts the specified element at the specified position.
list.add(1, "Element");
 addFirst(E e): Inserts the specified element at the beginning of the list.
list.addFirst("FirstElement");
 addLast(E e): Appends the specified element to the end of the list (same as add(E e)).
list.addLast("LastElement");

2. Removing Elements
 remove(): Removes the first element from the list.
list.remove();
 remove(int index): Removes the element at the specified position.
list.remove(1);
 remove(Object o): Removes the first occurrence of the specified element.
list.remove("Element");
 removeFirst(): Removes the first element (throws an exception if the list is empty).
list.removeFirst();
 removeLast(): Removes the last element (throws an exception if the list is empty).
list.removeLast();

3. Accessing Elements
 get(int index): Returns the element at the specified position.
String element = list.get(0);
 getFirst(): Returns the first element (throws an exception if the list is empty).
String first = list.getFirst();
 getLast(): Returns the last element (throws an exception if the list is empty).
String last = list.getLast();
4. Modifying Elements
 set(int index, E element): Replaces the element at the specified position with the specified
element.
list.set(1, "NewElement");

5. Checking Size
 size(): Returns the number of elements in the list.
int size = list.size();

6. Searching for Elements


 contains(Object o): Returns true if the list contains the specified element.
boolean exists = list.contains("Element");
 indexOf(Object o): Returns the index of the first occurrence of the specified element, or -1 if not
found.
int index = list.indexOf("Element");
 lastIndexOf(Object o): Returns the index of the last occurrence of the specified element.
int lastIndex = list.lastIndexOf("Element");

7. Iterating Through the List


 iterator(): Returns an iterator over the elements.
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
 listIterator(): Returns a list iterator for the list.
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
8. Adding and Removing in Queue Style
Since LinkedList implements Deque, it supports queue-style operations:
 offer(E e): Adds the element to the end of the list.
list.offer("Element");
 offerFirst(E e): Inserts the element at the beginning.
list.offerFirst("FirstElement");
 offerLast(E e): Adds the element to the end (same as offer()).
list.offerLast("LastElement");
 poll(): Removes and returns the first element (or null if the list is empty).
String first = list.poll();
 pollFirst(): Removes and returns the first element.
String first = list.pollFirst();
 pollLast(): Removes and returns the last element.
String last = list.pollLast();
 peek(): Retrieves the first element without removing it (returns null if empty).
String first = list.peek();
 peekFirst(): Retrieves the first element without removing it.
String first = list.peekFirst();
 peekLast(): Retrieves the last element without removing it.
String last = list.peekLast();

9. Converting to Array
 toArray(): Converts the list to an array.
Object[] array = list.toArray();

10. Clearing the List


 clear(): Removes all elements from the list.
list.clear();
Stack-Specific Methods (from java.util.Stack)

Method Description Example


empty()
Returns true if the stack is Stack<Integer> stack = new Stack<>();
empty, otherwise false.
peek()
Returns the top element of stack.push(10);
the stack without removing it.
Removes and returns the top
pop()
element of the stack. Throws System.out.println(stack.pop());
EmptyStackException if the
stack is empty.
push(Object o)
Pushes an element onto the stack.push(20);
top of the stack.
Returns the position of the
search(Object o) element (1-based index from System.out.println(stack.search(20));
the top), or -1 if not found.

1. Adding Elements

 push(E e): Pushes an element onto the stack.

stack.push("Element");

2. Removing Elements

 pop(): Removes and returns the top element of the stack. Throws EmptyStackException if the
stack is empty.

String element = stack.pop();

3. Accessing Elements

 peek(): Returns the top element of the stack without removing it. Throws
EmptyStackException if the stack is empty.

String top = stack.peek();

4. Checking Size

 size(): Returns the number of elements in the stack.

int size = stack.size();

5. Searching for Elements

 search(Object o): Returns the 1-based position of the element in the stack, or -1 if the
element is not found.
int position = stack.search("Element");

 contains(Object o): Checks if the stack contains the specified element.

boolean exists = stack.contains("Element");

6. Checking If Empty

 isEmpty(): Returns true if the stack is empty, otherwise false.

boolean empty = stack.isEmpty();

7. Iterating Through the Stack

 iterator(): Returns an iterator to iterate through the stack.

Iterator<String> iterator = stack.iterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}

 forEach(Consumer<? super E> action): Performs the specified action for each element.

stack.forEach(System.out::println);

8. Converting to Array

 toArray(): Converts the stack to an array.

Object[] array = stack.toArray();

 toArray(T[] a): Converts the stack to an array of the specified type.

String[] array = stack.toArray(new String[0]);

9. Reversing and Sorting

 Collections.reverse(List<E> list): Reverses the order of the stack elements (after


converting it to a list).

Collections.reverse(stack);

 Collections.sort(List<E> list): Sorts the stack elements (after converting it to a list).

Collections.sort(stack);

Queue methods in Java,


1. Adding Elements
 add(E e): Inserts the specified element into the queue. Throws an
exception if the queue is full.
queue.add("Element");
 offer(E e): Inserts the specified element into the queue. Returns false
if the queue is full.
queue.offer("Element");

2. Accessing Elements
 peek(): Retrieves the head of the queue without removing it. Returns null
if the queue is empty.
String head = queue.peek();
 element(): Retrieves the head of the queue without removing it. Throws an
exception if the queue is empty.
String head = queue.element();

3. Removing Elements
 remove(): Removes and returns the head of the queue. Throws an exception
if the queue is empty.
String head = queue.remove();
 poll(): Removes and returns the head of the queue. Returns null if the
queue is empty.
String head = queue.poll();

4. Checking Size
 size(): Returns the number of elements in the queue.
int size = queue.size();

5. Checking If Empty
 isEmpty(): Returns true if the queue is empty, otherwise false.
boolean empty = queue.isEmpty();

7. Converting to Array
 toArray(): Converts the queue to an array.
Object[] array = queue.toArray();

8. Clearing the Queue


 clear(): Removes all elements from the queue. (Only available for
implementations like LinkedList or PriorityQueue.)
queue.clear();

9. Special Methods for Deque


(If the queue is implemented as a Deque, e.g., LinkedList or ArrayDeque.)
 offerFirst(E e): Adds the element to the front of the queue.
deque.offerFirst("Element");
 offerLast(E e): Adds the element to the back of the queue.
deque.offerLast("Element");
 pollFirst(): Removes and returns the first element.
String first = deque.pollFirst();
 pollLast(): Removes and returns the last element.
String last = deque.pollLast();
 peekFirst(): Retrieves the first element without removing it.
String first = deque.peekFirst();
 peekLast(): Retrieves the last element without removing it.
String last = deque.peekLast();

STRING
1. Basic Methods
1. char charAt(int index)

Gets a character at a specific index


String s = "Hello";
System.out.println(s.charAt(1)); // e

2. int length()

Returns the length of the string.


String s = "Hello";
System.out.println(s.length()); // 5

3. boolean isEmpty()

Checks if the string is empty ("").


String s = "";
System.out.println(s.isEmpty()); // true

4. boolean isBlank() (Java 11+)

Checks if the string is empty or contains only whitespace.


String s = " ";
System.out.println(s.isBlank()); // true

2. Comparison Methods

5. boolean equals(Object anObject) Checks if two strings are equal.


String s1 = "hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // true

6. boolean equalsIgnoreCase(String anotherString)

Ignores case while comparing.


String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equalsIgnoreCase(s2)); // true

7. int compareTo(String anotherString)

Lexicographically compares two strings.


String s1 = "apple";
String s2 = "banana";
System.out.println(s1.compareTo(s2)); // Negative (-ve) value (because "apple"
< "banana")

8. int compareToIgnoreCase(String anotherString)


Ignores case while comparing lexicographically.
String s1 = "Apple";
String s2 = "apple";
System.out.println(s1.compareToIgnoreCase(s2)); // 0 (equal ignoring case)

3. Searching & Index Methods


9. boolean contains(CharSequence s)

Checks if a substring is present.


String s = "Hello World";
System.out.println(s.contains("World")); // true

10. boolean startsWith(String prefix)

Checks if a string starts with a given prefix.


String s = "Java";
System.out.println(s.startsWith("Ja")); // true

11. boolean startsWith(String prefix, int offset)

Checks if a substring starts at a specific index.


String s = "Hello World";
System.out.println(s.startsWith("World", 6)); // true

12. boolean endsWith(String suffix)

Checks if a string ends with a given suffix.


String s = "Hello.java";
System.out.println(s.endsWith(".java")); // true

13-20. indexOf and lastIndexOf Methods

Finds index of a character or substring.


String s = "banana";
System.out.println(s.indexOf('a')); // 1
System.out.println(s.indexOf('a', 2)); // 3
System.out.println(s.indexOf("na")); // 2
System.out.println(s.indexOf("na", 3)); // 4

System.out.println(s.lastIndexOf('a')); // 5
System.out.println(s.lastIndexOf("na")); // 4

4. Case Conversion Methods

21-24. toLowerCase() and toUpperCase()


String s = "Hello World";
System.out.println(s.toLowerCase()); // hello world
System.out.println(s.toUpperCase()); // HELLO WORLD

5. Substring & Extraction


25-26. substring(int beginIndex, int endIndex)

String s = "Hello World";


System.out.println(s.substring(6)); // World
System.out.println(s.substring(0, 5)); // Hello

27. char[] toCharArray()

Converts string to a character array.


String s = "Hello";
char[] chars = s.toCharArray();
System.out.println(chars[1]); // e

6. String Modification

28-36. replace(), trim(), strip()

String s = " Hello World ";


System.out.println(s.replace('o', 'x')); // Hellx Wxrld
System.out.println(s.trim()); // "Hello World"
System.out.println(s.strip()); // "Hello World" (Java 11+)

7. Splitting & Joining


37-39. split()

String s = "apple,banana,orange";
String[] arr = s.split(",");
System.out.println(arr[1]); // banana

40-41. join()

String result = String.join("-", "2025", "01", "30");


System.out.println(result); // 2025-01-30

8. Formatting Methods
42-43. format()

String formatted = String.format("Hello %s!", "Alice");


System.out.println(formatted); // Hello Alice!
9. Matching Methods

44-46. matches(), regionMatches()

String s = "Java123";
System.out.println(s.matches("\\w+")); // true

10. Other Utility Methods

47-53. intern(), codePointAt(), chars()

String s = "Hello";
System.out.println(s.intern() == s); // true

System.out.println(s.codePointAt(1)); // ASCII of 'e'

s.chars().forEach(System.out::println);

11. Value Conversion Methods


54-62. valueOf()

System.out.println(String.valueOf(100)); // "100"
System.out.println(String.valueOf(true)); // "true"
System.out.println(String.valueOf(3.14)); // "3.14"

MAP
1. Basic Methods

1. V put(K key, V value)

Adds a key-value pair.


Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
System.out.println(map); // {Alice=25, Bob=30}

2. void putAll(Map<? extends K, ? extends V> m)

Copies all mappings from another map.


Map<String, Integer> map2 = new HashMap<>();
map2.putAll(map);
System.out.println(map2); // {Alice=25, Bob=30}

3. V get(Object key)

Retrieves a value by key.


System.out.println(map.get("Alice")); // 25

4. V getOrDefault(Object key, V defaultValue)

Gets a value or returns a default if key is missing.


System.out.println(map.getOrDefault("Charlie", 18)); // 18

5. V remove(Object key)

Removes a key-value pair.


map.remove("Bob");
System.out.println(map); // {Alice=25}

6. boolean remove(Object key, Object value)

Removes a key only if it has the specified value.


map.put("Charlie", 35);
System.out.println(map.remove("Charlie", 36)); // false (wrong value)
System.out.println(map.remove("Charlie", 35)); // true

2. Checking and Validation Methods

7. boolean containsKey(Object key)

Checks if a key exists.


System.out.println(map.containsKey("Alice")); // true
8. boolean containsValue(Object value)

Checks if a value exists.


System.out.println(map.containsValue(25)); // true

9. boolean isEmpty()

Checks if the map is empty.


System.out.println(map.isEmpty()); // false

10. int size()

Returns the number of key-value pairs.


System.out.println(map.size()); // 1

3. View Methods (Keys, Values, Entries)

11. Set<K> keySet()

Returns a set of all keys.


System.out.println(map.keySet()); // [Alice]

12. Collection<V> values()

Returns a collection of all values.


System.out.println(map.values()); // [25]

13. Set<Map.Entry<K, V>> entrySet()

Returns a set of key-value pairs.


for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// Alice -> 25

4. Advanced Methods

14. V putIfAbsent(K key, V value)

Adds a key-value pair only if the key is missing.


map.putIfAbsent("Alice", 30); // Won't update because Alice already exists
map.putIfAbsent("David", 40);
System.out.println(map); // {Alice=25, David=40}
15. V compute(K key, BiFunction<? super K, ? super V, ? extends V>
remappingFunction)

Computes a new value for a key.


map.compute("Alice", (k, v) -> v + 5);
System.out.println(map); // {Alice=30, David=40}

16. V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Computes a value only if key is missing.


map.computeIfAbsent("Eve", k -> 50);
System.out.println(map); // {Alice=30, David=40, Eve=50}

17. V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V>


remappingFunction)

Computes a new value only if the key exists.


map.computeIfPresent("Alice", (k, v) -> v - 10);
System.out.println(map); // {Alice=20, David=40, Eve=50}

5. Bulk Operations

18. void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

Applies a function to all values.


map.replaceAll((k, v) -> v * 2);
System.out.println(map); // {Alice=40, David=80, Eve=100}

19. V replace(K key, V value)

Replaces a value only if key exists.


map.replace("David", 60);
System.out.println(map); // {Alice=40, David=60, Eve=100}

20. boolean replace(K key, V oldValue, V newValue)

Replaces a value only if it matches oldValue.


map.replace("Alice", 40, 45); // Updates only if Alice's value is 40
System.out.println(map); // {Alice=45, David=60, Eve=100}

6. Merge & Functional Methods

22. V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V>


remappingFunction)

Merges values for a key.


Map<String, Integer> map3 = new HashMap<>();
map3.put("A", 5);
map3.merge("A", 3, Integer::sum);
System.out.println(map3); // {A=8}

Complete Iteration in a Map in Java

In Java, a Map (e.g., HashMap, TreeMap, LinkedHashMap) stores key-value pairs, and we often need to
iterate over all entries to access keys, values, or both.

1. Iterating Over a Map – Complete Methods


There are three primary ways to iterate over a Map<K, V> in Java:

Method 1: Using entrySet() (Best for Both Key & Value)

This is the most efficient way when you need both keys and values.

Map<Integer, String> map = new HashMap<>();


map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Complete iteration using entrySet()


for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

✅ Why use entrySet()?

 It avoids multiple lookups (get() calls) for values, making it more efficient.

Method 2: Iterating Over Keys (Using keySet())

If you only need keys, you can iterate over keySet() and fetch values manually.

for (Integer key : map.keySet()) {


System.out.println("Key: " + key + ", Value: " + map.get(key));
}

🔴 Less efficient than entrySet() because map.get(key) requires an extra lookup.


Method 3: Iterating Over Values (Using values())

If you only need values, iterate over values().

for (String value : map.values()) {


System.out.println("Value: " + value);
}

✅ Efficient when keys are not needed.

2. Iterating Using Java 8+ Features


Method 4: Using forEach() (Lambda Expression)
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));

✅ Concise and recommended for Java 8+

Method 5: Using Streams (Java 8+)

If you need sorting or filtering, streams are useful:

map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey()) // Sorts by key
.forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue()));

✅ Powerful when working with large data and transformations.

Performance Comparison
Method Time Complexity Use Case
entrySet() (Best) O(n) Both keys & values
keySet() + get() O(n) (but extra lookup) If only keys are needed
values() O(n) If only values are needed
forEach() (Lambda) O(n) Concise Java 8+ solution
Streams O(n log n) (with sorting) Advanced filtering/sorting
Conclusion
 ✅ Use entrySet() for best efficiency when keys and values are required.
 ✅ Use forEach() or streams for modern, clean code.
 🚫 Avoid keySet() if you also need values, as it requires extra lookups.

Complete List of Map Methods


# Method Description
1 put(K, V) Inserts key-value
2 putAll(Map) Copies all mappings
3 get(K) Gets value by key
4 getOrDefault(K, V) Gets value or default
5 remove(K) Removes key
6 remove(K, V) Removes if value matches
7 containsKey(K) Checks for key
8 containsValue(V) Checks for value
9 isEmpty() Checks if empty
10 size() Returns size
11 keySet() Returns all keys
12 values() Returns all values
13 entrySet() Returns key-value pairs
14 putIfAbsent(K, V) Inserts if key is missing
15 compute(K, BiFunction) Computes new value
16 computeIfAbsent(K, Function) Computes if missing
17 computeIfPresent(K, BiFunction) Computes if exists
18 replaceAll(BiFunction) Replaces all values
19 replace(K, V) Replaces value
20 replace(K, V, V) Replaces if matches old value
21 clear() Clears map
22 merge(K, V, BiFunction) Merges values

SET
1. Creating a Set

Java provides three main implementations of Set:

 HashSet – Unordered, allows null, fastest operations.


 LinkedHashSet – Ordered by insertion.
 TreeSet – Sorted in ascending order.

import java.util.*;

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


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

2. Adding and Removing Elements

1. boolean add(E e)

Adds an element to the set (returns false if already present).

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


set.add("Apple");
set.add("Banana");
System.out.println(set); // [Apple, Banana]
System.out.println(set.add("Apple")); // false (already exists)

2. boolean remove(Object o)

Removes an element if present.

set.remove("Apple");
System.out.println(set); // [Banana]

3. boolean addAll(Collection<? extends E> c)

Adds all elements from another collection.

List<String> list = Arrays.asList("Cherry", "Dates");


set.addAll(list);
System.out.println(set); // [Banana, Cherry, Dates]

4. boolean removeAll(Collection<?> c)

Removes all elements from the specified collection.

set.removeAll(Arrays.asList("Cherry", "Dates"));
System.out.println(set); // [Banana]

5. boolean retainAll(Collection<?> c)

Keeps only elements present in another collection.

set.add("Apple");
set.add("Cherry");
set.retainAll(Arrays.asList("Apple"));
System.out.println(set); // [Apple]

6. void clear()

Removes all elements.

set.clear();
System.out.println(set.isEmpty()); // true

3. Checking Elements

7. boolean contains(Object o)
Checks if an element exists.

Set<Integer> numSet = new HashSet<>(Arrays.asList(1, 2, 3));


System.out.println(numSet.contains(2)); // true
System.out.println(numSet.contains(5)); // false

8. boolean containsAll(Collection<?> c)

Checks if all elements from a collection exist.

System.out.println(numSet.containsAll(Arrays.asList(1, 2))); // true


System.out.println(numSet.containsAll(Arrays.asList(1, 4))); // false

4. Iterating Through a Set

9. Iterator<E> iterator()

Gets an iterator for traversal.

Iterator<Integer> it = numSet.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 1
// 2
// 3

10. void forEach(Consumer<? super E> action)

Performs an action for each element.

numSet.forEach(System.out::println);

11. Spliterator<E> spliterator() (Advanced)

Provides a Spliterator for parallel processing.

Spliterator<Integer> spliterator = numSet.spliterator();


spliterator.forEachRemaining(System.out::println);

5. Size and Emptiness

12. int size()

System.out.println(numSet.size()); // 3

13. boolean isEmpty()

Checks if the set is empty.

System.out.println(numSet.isEmpty()); // false

6. Converting to Other Collections


14. Object[] toArray()

Converts the set to an array.

Object[] arr = numSet.toArray();


System.out.println(Arrays.toString(arr)); // [1, 2, 3]

7. Special Methods for TreeSet

16. E first()

Gets the smallest element.

Set<Integer> treeSet = new TreeSet<>(Arrays.asList(10, 20, 30));


System.out.println(((TreeSet<Integer>) treeSet).first()); // 10

17. E last()

Gets the largest element.

System.out.println(((TreeSet<Integer>) treeSet).last()); // 30

18. E lower(E e)

Finds the largest element less than the given value.

System.out.println(((TreeSet<Integer>) treeSet).lower(25)); // 20

19. E higher(E e)

Finds the smallest element greater than the given value.

System.out.println(((TreeSet<Integer>) treeSet).higher(25)); // 30

20. E ceiling(E e)

Finds the smallest element greater than or equal to the given value.

System.out.println(((TreeSet<Integer>) treeSet).ceiling(20)); // 20

21. E floor(E e)

Finds the largest element less than or equal to the given value.

System.out.println(((TreeSet<Integer>) treeSet).floor(25)); // 20

22. E pollFirst()

Retrieves and removes the first (smallest) element.

System.out.println(((TreeSet<Integer>) treeSet).pollFirst()); // 10
System.out.println(treeSet); // [20, 30]

23. E pollLast()
Retrieves and removes the last (largest) element.

System.out.println(((TreeSet<Integer>) treeSet).pollLast()); // 30
System.out.println(treeSet); // [20]

Complete List of Set Methods

# Method Description
1 add(E e) Adds an element
2 remove(Object o) Removes an element
3 addAll(Collection<? extends E> c) Adds all elements
4 removeAll(Collection<?> c) Removes multiple elements
5 retainAll(Collection<?> c) Retains common elements
6 clear() Clears the set
7 contains(Object o) Checks for an element
8 containsAll(Collection<?> c) Checks if all elements exist
9 iterator() Returns an iterator
10 forEach(Consumer<? super E> action) Iterates over elements
11 spliterator() Returns a Spliterator
12 size() Returns size
13 isEmpty() Checks if empty
14 toArray() Converts to an array
15 toArray(T[] a) Converts to a typed array
16 first() Returns first element (TreeSet)
17 last() Returns last element (TreeSet)
18 lower(E e) Element less than given value
19 higher(E e) Element greater than given value
20 ceiling(E e) Smallest ≥ given value
21 floor(E e) Largest ≤ given value
22 pollFirst() Removes first element
23 pollLast() Removes last element

Array
1. Declaring and Initializing an Array

// Declaring an array
int[] arr1 = new int[5]; // Default values: [0, 0, 0, 0, 0]
int[] arr2 = {1, 2, 3, 4, 5}; // Direct initialization
String[] names = new String[]{"Alice", "Bob", "Charlie"}; // String array

2. Accessing and Modifying Elements

arr1[0] = 10; // Assigning a value


System.out.println(arr2[2]); // Output: 3

3. Length of an Array

System.out.println(arr2.length); // Output: 5
4. Iterating Through an Array

1. Using for Loop

for (int i = 0; i < arr2.length; i++) {


System.out.print(arr2[i] + " ");
}
// Output: 1 2 3 4 5

2. Using for-each Loop

for (int num : arr2) {


System.out.print(num + " ");
}
// Output: 1 2 3 4 5

5. Java Built-in Array Methods (java.util.Arrays)

The java.util.Arrays class provides several useful methods.

1. Arrays.toString() – Convert Array to String

import java.util.Arrays;
System.out.println(Arrays.toString(arr2)); // Output: [1, 2, 3, 4, 5]

2. Arrays.sort() – Sorting an Array


int[] numbers = {5, 3, 8, 1, 2};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 5, 8]

3. Arrays.fill() – Fill an Array with a Value


int[] filledArray = new int[5];
Arrays.fill(filledArray, 7);
System.out.println(Arrays.toString(filledArray)); // Output: [7, 7, 7, 7, 7]

4. Arrays.copyOf() – Copy an Array


int[] copy = Arrays.copyOf(arr2, 3);
System.out.println(Arrays.toString(copy)); // Output: [1, 2, 3]

5. Arrays.copyOfRange() – Copy a Range from an Array


int[] rangeCopy = Arrays.copyOfRange(arr2, 1, 4);
System.out.println(Arrays.toString(rangeCopy)); // Output: [2, 3, 4]
6. Arrays.equals() – Compare Two Arrays
int[] arrA = {1, 2, 3};
int[] arrB = {1, 2, 3};
System.out.println(Arrays.equals(arrA, arrB)); // Output: true

7. Arrays.binarySearch() – Search for an Element (Sorted Array)


int[] sortedArr = {10, 20, 30, 40, 50};
System.out.println(Arrays.binarySearch(sortedArr, 30)); // Output: 2
System.out.println(Arrays.binarySearch(sortedArr, 25)); // Output: -3 (not found)

8. Arrays.parallelSort() – Faster Sorting (Large Arrays)


int[] largeArray = {12, 4, 7, 1, 9};
Arrays.parallelSort(largeArray);
System.out.println(Arrays.toString(largeArray)); // Output: [1, 4, 7, 9, 12]

9. Arrays.deepToString() – Print Multi-Dimensional Arrays


int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(matrix));
// Output: [[1, 2, 3], [4, 5, 6]]

10. Arrays.asList() – Convert Array to List


List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
System.out.println(list); // Output: [Apple, Banana, Cherry]

6. Multi-Dimensional Arrays
int[][] matrix = new int[2][3]; // 2 rows, 3 columns
int[][] numbers = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(numbers[1][2]); // Output: 6

Iterating a 2D Array
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
/*
Output:
1 2 3
4 5 6
*/

7. Java 8 Streams with Arrays

1. IntStream.of() – Convert Array to Stream


import java.util.stream.IntStream;
int[] nums = {1, 2, 3, 4, 5};
IntStream stream = IntStream.of(nums);
stream.forEach(System.out::print); // Output: 12345

2. Arrays.stream() – Sum of Array Elements


int sum = Arrays.stream(nums).sum();
System.out.println(sum); // Output: 15

3. Arrays.stream() – Filter Elements


Arrays.stream(nums).filter(n -> n % 2 == 0).forEach(System.out::println);
/*
Output:
2
4
*/

4. Arrays.stream() – Convert to List


List<Integer> numList = Arrays.stream(nums).boxed().toList();
System.out.println(numList); // Output: [1, 2, 3, 4, 5]

8. Summary of Java Array Methods

Method Description
toString() Converts array to a string
sort() Sorts an array
parallelSort() Sorts using parallel processing
fill() Fills an array with a value
copyOf() Copies an array
copyOfRange() Copies a subrange of an array
equals() Compares two arrays
binarySearch() Searches in a sorted array
asList() Converts array to a list
deepToString() Prints multi-dimensional arrays
stream() Converts array to stream
Method Description
sum() Computes the sum of array elements
filter() Filters elements using a condition

You might also like