本篇文章给大家分享的是有关TreeSet中的排序方式有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
直接上代码:
package exercise1;
public class Person implements Comparable{
private int id;
private String name;
public Person(int id, String name) {
super();
this.id = id;
this.name = 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 String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(Object o) {
if(o instanceof Person){
Person p=(Person)o;
return this.name.compareTo(p.name);
}
return 0;
}
}
package exercise1;
//TreeSet下的自然排序和定制排序
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import org.junit.Test;
//定制排序
public class DisOrder {
@Test
public void unNature(){
Comparator com=new Comparator() {
public int compare(Object o1, Object o2) {
if(o1 instanceof Person && o2 instanceof Person){
Person p1=(Person)o1;
Person p2=(Person)o2;
return p1.getName().compareTo(p2.getName());
}
return 0;
}
};
Set set=new TreeSet(com);
set.add(new Person(111,"MM"));
set.add(new Person(222,"DD"));
set.add(new Person(333,"GG"));
for(Object obj:set){
System.out.println(obj);
}
}
//自然排序
@Test
public void nature() {
Set set=new TreeSet();
set.add("aa");
set.add("bb");
set.add("ff");
set.add("zz");
for(Object obj:set){
System.out.println(obj);
}
}
}
以上就是TreeSet中的排序方式有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。