How to Find the Minimum or Maximum Element from the Vector in Java?
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:
- 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.
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.
- 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.
Vector elements : [100, 30, 7, 24, 13] Maximum Element in Vector : 100 Minimum Element in Vector : 7