Find the maximum element of a Vector in Java

Java 8Object Oriented ProgrammingProgramming

The maximum element of a Vector can be obtained using the java.util.Collections.max() method. This method contains a single parameter i.e. the Vector whose maximum element is determined and it returns the maximum element from the Vector.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Collections;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(7);
      vec.add(3);
      vec.add(9);
      vec.add(5);
      vec.add(8);
      System.out.println("The Vector elements are: " + vec);
      System.out.println("The maximum element of the Vector is: " + Collections.max(vec));
   }
}

The output of the above program is as follows −

The Vector elements are: [7, 3, 9, 5, 8]
The maximum element of the Vector is: 9

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. The vector is displayed. Collections.max() is used to find the maximum element of the Vector and that is displayed. A code snippet which demonstrates this is as follows −

Vector vec = new Vector();
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(5);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The maximum element of the Vector is: " + Collections.max(vec));
raja
Published on 07-Feb-2019 12:12:24
Advertisements