Friday 27 July 2012

Find maximum element of Java HashSet Example


 This java example shows how to find a maximum element of Java HashSet using max method of Collections class.


import java.util.HashSet;
import java.util.Collections;

public class FindMaximumOfHashSetExample {

 public static void main(String[] args) {

  // create a HashSet object
  HashSet hashSet = new HashSet();

  // Add elements to HashSet
  hashSet.add(123);
  hashSet.add(356);
  hashSet.add(456);
  hashSet.add(500);
  hashSet.add(50);

  /**
   * To find maximum element of Java HashSet use, static Object
   * max(Collection c) method of Collections class.
   * 
   * This method returns the maximum element of Java HashSet according to
   * its natural ordering.
   **/

  Object obj = Collections.max(hashSet);

  System.out.println("Maximum Element of Java HashSet is : " + obj);
 }
}


The output is:



Maximum Element of Java HashSet is : 500

No comments:

Post a Comment