Sunday 3 June 2018

TreeSet Example with User Defined Object

TreeSet Example

TreeSet Hierarchy

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Here in the below example we can see that Customer is a User Defined Object which I added in TreeSet. I have Overridden the compareTo() method based on my own Customer Age comparison in reverse order.

I have also added compareTo() method which is used to sort the customer based on their last name. Currently I have commented that part.



package com.gaurav.mapexample;

import java.util.Set;
import java.util.TreeSet;

class Customer implements Comparable<Customer>{
private String custFirstName;
private String custLastName;
private int custId;
public String getCustFirstName() {
return custFirstName;
}
public void setCustFirstName(String custFirstName) {
this.custFirstName = custFirstName;
}
public String getCustLastName() {
return custLastName;
}
public void setCustLastName(String custLastName) {
this.custLastName = custLastName;
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
@Override
public String toString() {
return "customer [custFirstName=" + custFirstName + ", custLastName=" + custLastName + ", custId=" + custId
+ "]";
}
public Customer(String custFirstName, String custLastName, int custId) {
super();
this.custFirstName = custFirstName;
this.custLastName = custLastName;
this.custId = custId;
}
//Sort by customer lastName;
/*@Override
public int compareTo(Object Obj) {
int result =0;
Customer customer =(Customer)Obj;
result = this.custLastName.compareTo(customer.custLastName);
return result;
}*/
//Sort by customer id in reverse order;
@Override
public int compareTo(Customer customer) {
if(this.custId > customer.getCustId())
return -1;
else if(this.custId < customer.getCustId())
return 1;
else
return 0;
}

}
public class TreeSetExample {
public static void main(String args[]){
Set<Customer> customerSet = new TreeSet<>();
customerSet.add(new Customer("Gaurav","Kumar", 1031));
customerSet.add(new Customer("Shivam","Aaditya", 1025));
customerSet.add(new Customer("Sahu","Sunita", 1011));
customerSet.add(new Customer("Suresh","Prasad", 999));
customerSet.add(new Customer("Kamana","Devi", 1003));

customerSet.stream().forEach(i->System.out.println(i));

}
}

Output:

customer [custFirstName=Gaurav, custLastName=Kumar, custId=1031]
customer [custFirstName=Shivam, custLastName=Aaditya, custId=1025]
customer [custFirstName=Sahu, custLastName=Sunita, custId=1011]
customer [custFirstName=Kamana, custLastName=Devi, custId=1003]
customer [custFirstName=Suresh, custLastName=Prasad, custId=999]

No comments:

Post a Comment