Java 按所有对象包含的字符串值对 Set 中的对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4132367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting objects within a Set by a String value that all objects contain
提问by Julio
Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.
好的,这是一个棘手的问题。我有一个集合列表。我想按顺序对集合中的对象进行排序。
Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.
想象每一组都压抑了学校的一个班级。每个集合都包含人物对象。person 对象保存 name 的 String 值。在循环遍历并写出它们之前,我想按名称排列集合中的人员。
Is there anywahy to use Collections.sort();
or something similar to achieve this?
无论如何要使用Collections.sort();
或类似的东西来实现这一目标?
for (Set<Person> s : listOfAllChildren) {
for (Person p : s) {
if(p.getClass().equalsIgnoreCase("Jones")){
System.out.println(p.getName());
}
else if...//carry on through other classes
}
}
I do know that 2+ children in a class may share the same name but please ignore this
我知道一个班级中有 2 个以上的孩子可能同名,但请忽略这一点
采纳答案by Nicolas Repiquet
A Set
has no notion of orderingbecause, well, it's a set.
ASet
没有排序的概念,因为它是一个集合。
There is a SortedSet
interface implemented by TreeSet
class that you can use. Simply provide an appropriate Comparator
to the constructor, or let your Person
class implements Comparable
.
您可以使用一个SortedSet
由TreeSet
类实现的接口。只需为Comparator
构造函数提供一个合适的,或者让你的Person
类实现Comparable
.
回答by sje397
You must implement Comparable
for your sortable objects (Person
etc).
您必须Comparable
为可排序的对象(Person
等)实施。
Then:
然后:
- Convert Set to List (some info here) since you can't sort a
Set
- Use
Collections.sort
- 将集合转换为列表(此处有一些信息),因为您无法对
Set
- 用
Collections.sort
or
或者
- Convert to a SortedSet(like a TreeSet)
- Use a Comparatorfor custom ordering
Examples:
例子:
import java.util.*;
class Person implements Comparable<Person> {
private String firstName, lastName;
public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName;}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getName() {return firstName + " " + lastName;}
public int compareTo(Person p) {
return lastName.compareTo(p.lastName);
}
}
class FirstNameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2){
return p1.getFirstName().compareTo(p2.getFirstName());
}
}
class Test {
public static void log(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Set<Person> people = new HashSet<Person>();
people.add(new Person("Bob", "Jones"));
people.add(new Person("Alice", "Yetti"));
log("Sorted list:");
List<Person> peopleList = new LinkedList<Person>();
peopleList.addAll(people);
Collections.<Person>sort(peopleList);
for (Person p : peopleList) {
log(p.getName());
}
log("TreeSet:");
TreeSet<Person> treeSet = new TreeSet<Person>();
treeSet.addAll(people);
for (Person p : treeSet) {
log(p.getName());
}
log("TreeSet (custom sort):");
TreeSet<Person> treeSet2 = new TreeSet<Person>(new FirstNameComparator());
treeSet2.addAll(people);
for (Person p : treeSet2) {
log(p.getName());
}
}
};
回答by npinti
You could make your Person class implement the Comparableinterface as shown hereand then sort them accordingly.
回答by Nico Huysamen
Yes! This you can definitely use Collection.sort(). But you will need to either use a sorted set (like TreeSet). Or, alternatively, you can first insert all the elements in the Set to a List.
是的!这你绝对可以使用Collection.sort()。但是您将需要使用排序集(如 TreeSet)。或者,您可以先将 Set 中的所有元素插入到列表中。
Then, your Person class needs to implement Comparable, as this interface will be called by the Collections.sort() when it tries to decide in which order to place them. So it can be something simple like:
然后,你的 Person 类需要实现 Comparable,因为当 Collections.sort() 试图决定它们的放置顺序时,它会调用这个接口。所以它可以是简单的,比如:
public class Person implements Comparable<Person> {
...
@Override
public int compareTo(Person p) {
return this.name.compareTo(p.name);
}
}
If using a TreeSet, it should be sorted already. Otherwise, if using a List, simply call Collections.sort(List l) on each list.
如果使用 TreeSet,它应该已经排序。否则,如果使用列表,只需在每个列表上调用 Collections.sort(List l)。
回答by Alex Nikolaenkov
You can consider using TreeSet to store objects. And when sorting create new TreeSet with custom comparator for your Person objects. I do not suggest using Collection.sort because AFAIR it can sort only lists.
可以考虑使用TreeSet来存储对象。并在排序时为您的 Person 对象创建带有自定义比较器的新 TreeSet。我不建议使用 Collection.sort 因为 AFAIR 它只能对列表进行排序。
回答by Qwerky
You may want to look at using a SortedSet
for example a TreeSet
. This allows you to provide a Comparator
which in your case can compare the name of the Person
.
您可能想看看使用 aSortedSet
例如 a TreeSet
。这允许您提供Comparator
在您的情况下可以比较Person
.
回答by ravthiru
With Java 8 you can sort the Set
of persons and generate List
of persons which are sorted as follows.
使用 Java 8,您可以对人员进行排序Set
并生成List
按如下方式排序的人员。
List<Person> personList = personSet.stream().sorted((e1, e2) ->
e1.getName().compareTo(e2.getName())).collect(Collectors.toList());