How to Find the Minimum or Maximum Element from the Vector in Java?
Last Updated :
04 Apr, 2023
The Collection is a framework offered by Java that provides an architecture to store a group of objects. One such collection is Vector(). There are many ways through which we can find the minimum and maximum elements in a Vector. These methods have been discussed below:
Methods:
- Using Collection.min() and Collection.max() methods.
- Using Iterating over vector elements setting min-max.
Method 1: Using Collections.min() and Collections.max() method
Collections package offers a static method of finding the minimum and maximum in a collection. These methods are Collections.max() and Collections.min().
- Collections.max() finds the maximum element
- Collections.min() finds the minimum element in a collection.
Example
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
Vector<Integer> V = new Vector<Integer>();
V.add( 1 );
V.add( 2 );
V.add( 3 );
V.add( 4 );
V.add( 5 );
System.out.println( "Vector elements : " + V);
int minNumber = Collections.min(V);
int maxNumber = Collections.max(V);
System.out.println( "Maximum Number in Vector is : "
+ maxNumber);
System.out.println( "Minimum Number in Vector is : "
+ minNumber);
}
}
|
Output
Vector elements : [1, 2, 3, 4, 5]
Maximum Number in Vector is : 5
Minimum Number in Vector is : 1
Method 2: Using Iterating over vector elements setting min-max.
Approach:
- Take a variable say minNumber, and initialized to the maximum value later on to compare and update.
- Take a variable say maxNumber, and initialized to minimum value later on to compare an update.
- Iterate through Vector and compare each element with the above two-variable –
- If the number is less than minNumber, update the value of minNumber.
- If the number is greater than maxNumber, update the value of maxNumber.
Example
Java
import java.util.*;
import java.lang.Integer;
class GFG {
public static void main(String[] args)
{
int minValue = Integer.MAX_VALUE;
int maxValue = Integer.MIN_VALUE;
Vector<Integer> V = new Vector<Integer>();
V.add( 100 );
V.add( 30 );
V.add( 7 );
V.add( 24 );
V.add( 13 );
System.out.println( "Vector elements : " +V);
for (Integer i : V) {
if (i > maxValue) {
maxValue = i;
}
if (i < minValue) {
minValue = i;
}
}
System.out.println( "Maximum Element in Vector : "
+ maxValue);
System.out.println( "Minimum Element in Vector : "
+ minValue);
}
}
|
Output
Vector elements : [100, 30, 7, 24, 13]
Maximum Element in Vector : 100
Minimum Element in Vector : 7
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...