A Java Collection can contain multiple elements, and sometimes we need to compare these elements to find the smallest and largest values.
- Collections.min(): Returns the smallest element in the collection.
- Collections.max(): Returns the largest element in the collection.
Approach
- Create a collection and add elements to it.
- Use Collections.min() to find the minimum element.
- Use Collections.max() to find the maximum element.
- Compare the minimum and maximum values.
- If both are equal, all elements in the collection are equal; otherwise, print the minimum and maximum values.
Syntax forCollections.min()
Collections.min(collection)
Returns the smallest element in the specified collection.
Syntax forCollections.max()
Collections.max(collection)
Returns the largest element in the specified collection.
import java.util.*;
class CompareCollection {
public static void main(String[] args)
{
// Create an ArrayList
List<Integer> numbers = new ArrayList<>();
// Add elements to the list
numbers.add(27);
numbers.add(14);
numbers.add(39);
numbers.add(8);
numbers.add(21);
// Find minimum and maximum elements
int minimum = Collections.min(numbers);
int maximum = Collections.max(numbers);
// Compare minimum and maximum values
if (minimum == maximum) {
System.out.println("All elements are equal");
}
else {
System.out.println("Minimum value: " + minimum);
System.out.println("Maximum value: " + maximum);
}
}
}
Output
Minimum value: 8 Maximum value: 39
Explanation: The numbers list contains five integer values. Collections.min(numbers) returns 8, which is the smallest element, while Collections.max(numbers) returns 39, which is the largest element. Since the two values are different, the program prints both the minimum and maximum values.
Check Whether All Elements Are Equal In Arraylist
import java.util.*;
class CompareCollection {
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<>();
numbers.add(25);
numbers.add(25);
numbers.add(25);
numbers.add(25);
int minimum = Collections.min(numbers);
int maximum = Collections.max(numbers);
// Check whether all elements are equal
if (minimum == maximum) {
System.out.println("All elements are equal");
}
else {
System.out.println("Minimum value: " + minimum);
System.out.println("Maximum value: " + maximum);
}
}
}
Output
All elements are equal
Explanation: All elements in the list contain the value 25. Therefore, both Collections.min() and Collections.max() return 25. Since the minimum and maximum values are equal, the program concludes that all elements are equal.