This question already has an answer here:
这个问题在这里已有答案:
- Sorting objects within a Set by a String value that all objects contain 7 answers
通过String值对Set内的对象进行排序,所有对象包含7个答案
I know that we can use TreeSet to sort Strings and numbers in an natural order. What if there is a Set of objects?
我知道我们可以使用TreeSet以自然顺序对字符串和数字进行排序。如果有一组对象怎么办?
For example:
I have a Person class
{
private String firstName;
private String lastName;
private int age;
}
Set person = new TreeSet();
设置person = new TreeSet();
I want person sorted by firstName when I initialize person.
我想在初始化人时按firstName排序的人。
1 个解决方案
#1
1
Both Comparable
and Comparator
work for you, but I suggest Comparator
because it doesn't require you modify Person
class, you only need the write an implementation class based on the sorting attribute, therefore Comparator
is much more flexiable:
Comparable和Comparator都适合你,但我建议使用Comparator,因为它不需要你修改Person类,你只需要根据sorted属性编写一个实现类,因此Comparator更灵活:
import java.util.Comparator;
public class FirstNameComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
String name1 = o1.getFirstName();
String name2 = o2.getFirstName();
return name1.compareTo(name2);
}
}
//instantiate TreeSet instance with FirstNameComparator
Set<Person> ts = new TreeSet<>(new FirstNameComparator());
#1
1
Both Comparable
and Comparator
work for you, but I suggest Comparator
because it doesn't require you modify Person
class, you only need the write an implementation class based on the sorting attribute, therefore Comparator
is much more flexiable:
Comparable和Comparator都适合你,但我建议使用Comparator,因为它不需要你修改Person类,你只需要根据sorted属性编写一个实现类,因此Comparator更灵活:
import java.util.Comparator;
public class FirstNameComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
String name1 = o1.getFirstName();
String name2 = o2.getFirstName();
return name1.compareTo(name2);
}
}
//instantiate TreeSet instance with FirstNameComparator
Set<Person> ts = new TreeSet<>(new FirstNameComparator());