TreeSet With User Defined Object
TreeSet is an implementation of Set, SortedSet, NavigableSet. As it implements SortedSet thus elements are ordered using their natural ordering. As it implements Set, so TreeSet does not allow duplicates
Result:
User [id=33, name=Aaditya]
User [id=56, name=Shivam]
User [id=101, name=Gaurav]
User [id=202, name=Siva]
If we analyze the result, then we will find that there is only one entry for the user id 101. But we have added that id two times. Hence we can say that duplicates are not allowed in TreeSet. Here we have implemented Comparable interface in the User class and provided the compareTo() method which contains the logic to compare two User class objects based on their id. We have defined two user objects to be equal if their Id is equal.
The compareTo() method is defined such that the user objects are sorted in ascending order of id.
TreeSet is an implementation of Set, SortedSet, NavigableSet. As it implements SortedSet thus elements are ordered using their natural ordering. As it implements Set, so TreeSet does not allow duplicates
Demo Example:-
package com.gaurav.samples;
import java.util.Set;
import java.util.TreeSet;
class User implements Comparable<User>{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public int compareTo(User user) {
if(this.id > user.id)
return 1;
else if(this.id < user.id)
return -1;
else return 0;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<User> userSet = new TreeSet<User>();
userSet.add(new User(101, "Gaurav"));
userSet.add(new User(33, "Aaditya"));
userSet.add(new User(56, "Shivam"));
userSet.add(new User(202, "Siva"));
userSet.add(new User(101, "Gaurav"));
userSet.forEach(i-> System.out.println(i));
}
}
User [id=33, name=Aaditya]
User [id=56, name=Shivam]
User [id=101, name=Gaurav]
User [id=202, name=Siva]
If we analyze the result, then we will find that there is only one entry for the user id 101. But we have added that id two times. Hence we can say that duplicates are not allowed in TreeSet. Here we have implemented Comparable interface in the User class and provided the compareTo() method which contains the logic to compare two User class objects based on their id. We have defined two user objects to be equal if their Id is equal.
The compareTo() method is defined such that the user objects are sorted in ascending order of id.
No comments:
Post a Comment