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

Collections in Java

The java.util.Collections class in Java provides static methods for common operations on collections such as sorting, reversing, and searching. Key methods include sort(), reverse(), max(), min(), and binarySearch(), which can be applied to Lists and other collections. Understanding these methods is essential for effective manipulation of collections in Java programming.
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)
24 views

Collections in Java

The java.util.Collections class in Java provides static methods for common operations on collections such as sorting, reversing, and searching. Key methods include sort(), reverse(), max(), min(), and binarySearch(), which can be applied to Lists and other collections. Understanding these methods is essential for effective manipulation of collections in Java programming.
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
You are on page 1/ 13

The java.util.

Collections class is a utility class in Java that provides several


static methods to operate on or return collections (such as List, Set, Map, etc.).
These methods can perform tasks like sorting, reversing, finding the maximum or
minimum, binary searching, and more. It works with collections (like List) and is
very useful for common collection operations.

Let's go through the concepts and methods step by step.

Key Concepts:

1. List: A List is a type of collection that represents an ordered sequence of


elements. You can access elements in a List using an index (just like
arrays). In Java, the most commonly used List implementations are
ArrayList and LinkedList.
2. Collections Utility Class: This class contains methods that can be applied
to collections (like List, Set, etc.) to perform common tasks, such as
sorting, reversing, or searching. This class provides algorithms for
manipulating collections.

Important Methods in Collections:

1. sort(List<T> list):

o This method sorts the elements of the list in ascending order.


o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 6);
Collections.sort(numbers);
System.out.println(numbers); // Output: [1, 2, 5, 6, 9]

2. reverse(List<T> list):

o This method reverses the order of elements in the list.


o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
Collections.reverse(numbers);
System.out.println(numbers); // Output: [4, 3, 2, 1]

3. max(Collection<T> collection):

o This method returns the maximum element in the collection.


o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(3, 7, 1, 4);
int maxValue = Collections.max(numbers);
System.out.println(maxValue); // Output: 7

4. min(Collection<T> collection):

o This method returns the minimum element in the collection.


o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(3, 7, 1, 4);
int minValue = Collections.min(numbers);
System.out.println(minValue); // Output: 1
5. binarySearch(List<T> list, T key):

o This method performs binary search on a sorted list for a specific


element.
o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(1, 3, 4, 6, 7);
int index = Collections.binarySearch(numbers, 4);
System.out.println(index); // Output: 2 (the index of 4)

o Note: The list must be sorted before performing a binary search.

Example: Using Collections Methods

java
Copy code
import java.util.*;

public class CollectionDemo {


public static void main(String[] args) {
List<Integer> arr1 = Arrays.asList(3, 1, 5, 7, 2);

// Sort the list in ascending order


Collections.sort(arr1);
System.out.println("Sorted List: " + arr1); // Output: [1, 2,
3, 5, 7]

// Reverse the list


Collections.reverse(arr1);
System.out.println("Reversed List: " + arr1); // Output: [7,
5, 3, 2, 1]
// Find the maximum value in the list
int maxValue = Collections.max(arr1);
System.out.println("Max Value: " + maxValue); // Output: 7

// Find the minimum value in the list


int minValue = Collections.min(arr1);
System.out.println("Min Value: " + minValue); // Output: 1

// Perform binary search for element 3


Collections.sort(arr1); // Binary search requires the list to
be sorted
int index = Collections.binarySearch(arr1, 3);
System.out.println("Index of 3: " + index); // Output: 2
}
}

Explanation of Key Methods Used in Your Example Code:

1. arr1.get(i):

o This is used to access the i-th element in the list arr1. Unlike arrays
where you use arr[i], for lists, you use list.get(index).
o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(5, 2, 9);
System.out.println(numbers.get(0)); // Output: 5

2. size():

o This is used to get the number of elements in a List. Unlike arrays


where you use arr.length, for lists, you use list.size().
o Example:

java
Copy code
List<Integer> numbers = Arrays.asList(5, 2, 9);
System.out.println(numbers.size()); // Output: 3

3. Collections.sort():

o Sorts the list in ascending order.


o Usage:

java
Copy code
List<Integer> numbers = Arrays.asList(3, 1, 4, 5);
Collections.sort(numbers);
System.out.println(numbers); // Output: [1, 3, 4, 5]

Example Task: Find the Minimum Value of the Sum of Products

java
Copy code
import java.util.*;

class Solution {
public long minValue(List<Integer> arr1, List<Integer> arr2) {
// Sort arr1 in ascending order
Collections.sort(arr1);

// Sort arr2 in ascending order and reverse it


Collections.sort(arr2);
Collections.reverse(arr2);

long k = 0; // Initialize the result sum


// Calculate the sum of products of smallest in arr1 with
largest in arr2
for (int i = 0; i < arr1.size(); i++) {
k += (long) arr1.get(i) * arr2.get(i); // Multiply
corresponding elements
}

return k; // Return the result


}

public static void main(String[] args) {


Solution solution = new Solution();
List<Integer> arr1 = Arrays.asList(6, 1, 9, 5, 4);
List<Integer> arr2 = Arrays.asList(3, 4, 8, 2, 4);

long result = solution.minValue(arr1, arr2);


System.out.println("Minimum Sum of Products: " + result); //
Output: 80
}
}

Key Takeaways:

 Collections Utility Class: Provides many useful methods for manipulating


collections (sort(), reverse(), max(), min(), etc.).
 List Access: Use get(index) to access elements and size() to get the
length.
 Sorting and Reversing: These are common operations to help achieve the
optimal solution in problems like minimizing or maximizing the sum of
products.

Let me know if you need more details or further clarification!


You said:

arr1.get(i) is there any other like this like add put

ChatGPT said:

ChatGPT

Yes, in Java, List and other collections (like Set, Map, etc.) provide several
methods to manipulate and work with the elements. Here's a quick overview of
commonly used methods for various collection types:

1. List (e.g., ArrayList, LinkedList)

 get(int index):

o Returns the element at the specified position in the list.


o Example:

java
Copy code
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2,
3));
System.out.println(list.get(1)); // Output: 2

 add(E element):

o Adds the specified element to the end of the list.


o Example:

java
Copy code
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list); // Output: [Apple, Banana]

 add(int index, E element):

o Inserts the specified element at the specified position in the list.


o Example:

java
Copy code
List<String> list = new ArrayList<>(Arrays.asList("Apple",
"Banana"));
list.add(1, "Orange");
System.out.println(list); // Output: [Apple, Orange,
Banana]

 remove(int index):

o Removes the element at the specified position in the list.


o Example:

java
Copy code
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2,
3));
list.remove(1); // Removes element at index 1
System.out.println(list); // Output: [1, 3]

 remove(Object o):

o Removes the first occurrence of the specified element from the list.
o Example:

java
Copy code
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2,
3));
list.remove(Integer.valueOf(2)); // Removes element '2'
System.out.println(list); // Output: [1, 3]

 set(int index, E element):

o Replaces the element at the specified position in the list with the
specified element.
o Example:

java
Copy code
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2,
3));
list.set(1, 99); // Replaces the element at index 1
System.out.println(list); // Output: [1, 99, 3]

 contains(Object o):

o Returns true if the list contains the specified element.


o Example:

java
Copy code
List<String> list = new ArrayList<>(Arrays.asList("Apple",
"Banana"));
System.out.println(list.contains("Banana")); // Output:
true

 clear():

o Removes all elements from the list.


o Example:

java
Copy code
List<String> list = new ArrayList<>(Arrays.asList("Apple",
"Banana"));
list.clear();
System.out.println(list); // Output: []

 size():

o Returns the number of elements in the list.


o Example:

java
Copy code
List<String> list = new ArrayList<>(Arrays.asList("Apple",
"Banana"));
System.out.println(list.size()); // Output: 2

2. Set (e.g., HashSet, TreeSet)

 add(E element):

o Adds the specified element to the set if it is not already present.


o Example:

java
Copy code
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
System.out.println(set); // Output: [1, 2]

 contains(Object o):

o Returns true if the set contains the specified element.


o Example:
java
Copy code
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));
System.out.println(set.contains(2)); // Output: true

 remove(Object o):

o Removes the specified element from the set if present.


o Example:

java
Copy code
Set<String> set = new HashSet<>(Arrays.asList("Apple",
"Banana"));
set.remove("Banana");
System.out.println(set); // Output: [Apple]

 size():

o Returns the number of elements in the set.


o Example:

java
Copy code
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));
System.out.println(set.size()); // Output: 3

3. Map (e.g., HashMap, TreeMap)

 put(K key, V value):

o Associates the specified value with the specified key in the map.
o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
System.out.println(map); // Output: {Apple=1, Banana=2}

 get(Object key):

o Returns the value to which the specified key is mapped, or null if the
map contains no mapping for the key.
o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
System.out.println(map.get("Apple")); // Output: 1

 containsKey(Object key):

o Returns true if the map contains a mapping for the specified key.
o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
System.out.println(map.containsKey("Apple")); // Output:
true

 remove(Object key):

o Removes the mapping for the specified key from the map if present.
o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.remove("Apple");
System.out.println(map); // Output: {}

 size():

o Returns the number of key-value mappings in the map.


o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
System.out.println(map.size()); // Output: 1

 clear():

o Removes all of the mappings from the map.


o Example:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.clear();
System.out.println(map); // Output: {}

You might also like