In this article, we will understand how to compare elements in a collection. The Collection is a framework that provides architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Below is a demonstration of the same −
Suppose our input is −
Input list: [300, 500, 180, 450, 610]
The desired output would be −
Min value of our list : 180 Max value of our list : 610
Algorithm
Step 1 - START Step 2 - Declare a list namely input_list Step 3 - Define the values. Step 4 - Using the function = Collections.min() and Collections.max(), we fetch the min and max values of the collection. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*;
public class Demo {
public static void main(String[] args){
List<Integer> input_list = new ArrayList<>();
input_list.add(300);
input_list.add(500);
input_list.add(180);
input_list.add(450);
input_list.add(610);
System.out.println("The list is defined as: " +input_list);
int minimum_value = Collections.min(input_list);
int maximum_value = Collections.max(input_list);
if (minimum_value == maximum_value) {
System.out.println("All the elements of the list are equal");
}
else {
System.out.println("\nMin value of our list : " + minimum_value);
System.out.println("Max value of our list : " + maximum_value);
}
}
}Output
The list is defined as: [300, 500, 180, 450, 610] Min value of our list : 180 Max value of our list : 610
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*;
public class Demo {
static void min_max(List<Integer> input_list){
int minimum_value = Collections.min(input_list);
int maximum_value = Collections.max(input_list);
if (minimum_value == maximum_value) {
System.out.println("All the elements of the list are equal");
}
else {
System.out.println("\nMin value of our list : " + minimum_value);
System.out.println("Max value of our list : " + maximum_value);
}
}
public static void main(String[] args){
List<Integer> input_list = new ArrayList<>();
input_list.add(300);
input_list.add(500);
input_list.add(180);
input_list.add(450);
input_list.add(610);
System.out.println("The list is defined as: " +input_list);
min_max(input_list);
}
}Output
The list is defined as: [300, 500, 180, 450, 610] Min value of our list : 180 Max value of our list : 610