Saturday, 26 April 2014

TreeSet : lower : Get the highest Element currently in the Set

E lower()
Returns the greatest element in this set strictly less than the given element, or null if there is no such element.

import java.util.*;

class TreeSetLower{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements to mySet */
  for(int i=20; i>=0; i-=2)
   mySet.add(i);
 
  for(int i=0; i<=20; i+=2){
   System.out.print("Greatest Element strictly less than ");
   System.out.println(i +" is " + mySet.lower(i));
  }
 }
}

Output
Greatest Element strictly less than 0 is null
Greatest Element strictly less than 2 is 0
Greatest Element strictly less than 4 is 2
Greatest Element strictly less than 6 is 4
Greatest Element strictly less than 8 is 6
Greatest Element strictly less than 10 is 8
Greatest Element strictly less than 12 is 10
Greatest Element strictly less than 14 is 12
Greatest Element strictly less than 16 is 14
Greatest Element strictly less than 18 is 16
Greatest Element strictly less than 20 is 18

1. throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

import java.util.*;

class TreeSetLowerNullPointer{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements to mySet */
  for(int i=20; i>=0; i-=2)
   mySet.add(i);
 
  mySet.lower(null);
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1188)
        at java.util.TreeMap.getLowerEntry(TreeMap.java:487)
        at java.util.TreeMap.lowerKey(TreeMap.java:703)
        at java.util.TreeSet.lower(TreeSet.java:414)
        at TreeSetLowerNullPointer.main(TreeSetLowerNullPointer.java:11)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment