1.Basic Java example program sort student object descending order by id using treeset

  1. package com.TreeSetExamplePrograms;

  2. public Class Employee Implements Comparable<Employee>{ 

  3.     String name;
  4.     int id;
  5.     
  6.     public String getName() {
  7.         return name;
  8.     }
  9.  
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.  
  14.     public int getId() {
  15.         return id;
  16.     }
  17.  
  18.     public void setId(int id) {
  19.         this.id = id;
  20.     }
  21.  
  22.     Employee (String name, int id){
  23.         this.name=name;
  24.         this.id=id;
  25.     }
  26.  
  27.     @Override    public int compareTo(Employee obj) {
  28.         if (this.getId() == obj.getId()) return 0;
  29.         else
  30.         
  31.         if (this.getId() < obj.getId()) return 1;
  32.         else return -1;
  33.             
  34. }
  35.  
  36. }



  1. package com.TreeSetExamplePrograms;

  2. public Class Test{ 
  3. public static void main(String args[]) {
  4. //create TreeSet object
  5.  
  6. TreeSet<Employee> treeSet = new TreeSet<Employee>();     
  7.      
  8.        //add elements to TreeSet
  9.     treeSet.add(new Employee("abc",1));
  10.     treeSet.add(new Employee("xyz",2));
  11.     treeSet.add(new Employee("ssd",3));
  12.     treeSet.add(new Employee("ert",4));
  13.          
  14.     Iterator itr = treeSet.iterator();
  15.  
  16.  while(itr.hasNext()){
  17.  
  18.      Employee obj= (Employee)itr.next();
  19.      System.out.println(obj.getName()+"  "+obj.getId()); 

  20.   }         

  21. }
  22. }



Output:

  1. ert  4
  2. ssd  3
  3. xyz  2
  4. abc  1 

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu