Java Collection How to - Find maximum/Minimum element of Set








Question

We would like to know how to find maximum/Minimum element of Set.

Answer

 /* ww w  .  j a  va 2  s.  c  o  m*/


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

public class Main {

  public static void main(String[] args) {
    HashSet<Long> hashSet = new HashSet<Long>();
    hashSet.add(new Long("1111111111"));
    hashSet.add(new Long("2222222222"));
    hashSet.add(new Long("3333333333"));
    hashSet.add(new Long("4444444444"));
    hashSet.add(new Long("5555555555"));

    Object obj = Collections.max(hashSet);
    //Object obj = Collections.min(hashSet);
    System.out.println(obj);
  }
}

The code above generates the following result.