package com.jason.springsentinel;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class Test {
//根据person的 ID排序
public static TreeSet personTreeSet=new TreeSet<>(new MyCompartor());
//根据person的 score排序
public static TreeSet personTreeSetScore=new TreeSet<>(new MyCompartorScore());
public static void main(String[] args) {
//1.根据id排序
personTreeSet.add(new Person("jason",100,100));
personTreeSet.add(new Person("jerry",1,90));
personTreeSet.add(new Person("jerry",3,90));
personTreeSet.add(new Person("jerry",2,90));
display(personTreeSet);
//2.根据score排序
personTreeSetScore.add(new Person("jason",100,60));
personTreeSetScore.add(new Person("jerry",1,50));
personTreeSetScore.add(new Person("tom",3,90));
personTreeSetScore.add(new Person("henson",5,44));
personTreeSetScore.add(new Person("henny",2,44));
display(personTreeSetScore);
}
public static void display(TreeSet personTreeSets)
{
Iterator iterator=personTreeSets.iterator();
System.out.println(personTreeSets.size());
while (iterator.hasNext())
{
System.out.println(iterator.next().toString());
}
}
}
class MyCompartor implements Comparator
{
@Override
public int compare(Person o1, Person o2) {
int num=o1.id-o2.id;
if(num==0)
{
num=o1.getName().hashCode()-o2.getName().hashCode();
}
return num;
}
}
class MyCompartorScore implements Comparator
{
@Override
public int compare(Person o1, Person o2) {
int num=o1.getScore()-o2.getScore();
if(num==0)
{
num=o1.getName().hashCode()-o2.getName().hashCode();
}
if(num==0)
{
num=o1.getId()-o2.getId();
}
if(num==0)
{
num=o1.getName().hashCode()-o2.getName().hashCode();
}
return num;
}
}
class Person
{
String name;
int id;
int score;
public Person(String name, int id, int score) {
this.name = name;
this.id = id;
this.score = score;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
", id=" + id +
", score=" + score +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}