» » » Get lowest and highest value stored in Java TreeSet example

1.Basic Java example program get lowest and highest values from treeset

  1. package com.TreeSetExamplePrograms;

  2. public Class TreeSetGetLowestAndHighestDemo{ 
  3.  
  4. public static void main(String args[]) {
  5. //create TreeSet object
  6.  
  7.  
  8.  TreeSet<Integer> treeSet = new TreeSet<Integer>();
  9.        
  10.  //add elements to TreeSet
  11.   treeSet.add(1);
  12.   treeSet.add(3);
  13.   treeSet.add(2);
  14.   treeSet.add(5);
  15.   treeSet.add(6);
  16.   treeSet.add(7);
  17.   treeSet.add(8);
  18.   treeSet.add(9);
  19.   treeSet.add(10);
  20.           
  21.  System.out.println(treeSet);
  22.           
  23.  System.out.println("First element in treeset : " + treeSet.first());           
  24.    
  25.  System.out.println("Last element in treeste" + treeSet.last()); 


  26. }
  27. }


Output:


  1. [1, 2, 3, 4, 5, 6, 7, 8, 9,10]
  2. First element in treeset :1
  3. Last element in treeset :10


2.Basic Java example program print elements of treeset using iterator


  1. package com.TreeSetExamplePrograms;

  2. public Class TreeSetDemo{ 
  3.  
  4. public static void main(String args[]) {
  5. //create TreeSet object
  6.  
  7.  TreeSet<String> treeSet = new TreeSet<String>();
  8.  
  9.    //add elements to TreeSet
  10.     treeSet.add("I");
  11.     treeSet.add("N");
  12.     treeSet.add("S");
  13.     treeSet.add("T");
  14.     treeSet.add("A");
  15.     treeSet.add("N");
  16.     treeSet.add("C");
  17.     treeSet.add("E");
  18.           
  19.     treeSet.add("O");
  20.     treeSet.add("F");
  21.   
  22. Iterator itr = treeSet.iterator();
  23. while(itr.hasNext()){
  24.              System.out.println(itr.next());
  25. }

  26. }
  27. }




Output:

  1. A
  2. C
  3. E
  4. F
  5. I
  6. N
  7. O
  8. S
  9. T

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu