Friday 27 July 2012

Find Minimum element of Java HashSet Example


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


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

public class FindMinimumOfHashSetExample {

 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 minimum element of Java HashSet use, static Object
   * min(Collection c) method of Collections class.
   * 
   * This method returns the minimum element of Java HashSet according to
   * its natural ordering.
   **/

  Object obj = Collections.min(hashSet);

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


The output is:



Minimum Element of Java HashSet is : 50

No comments:

Post a Comment