根据其成员项的“toString”值按字母顺序对 Java 集合进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554769/
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
Alphabetically Sort a Java Collection based upon the 'toString' value of its member items
提问by Tom Neyland
Assume I have a user defined Java class called Foo such as:
假设我有一个名为 Foo 的用户定义的 Java 类,例如:
public class Foo
{
private String aField;
@Override
public String toString()
{
return aField;
}
}
And a Collection such as:
和一个集合,例如:
List<Foo> aList;
What I am looking to do is to sort the List alphabetically based upon each member's returned '.toString()' value.
我想要做的是根据每个成员返回的 '.toString()' 值按字母顺序对 List 进行排序。
I have tried using the Collections.sort() method, but the result was not what I was attempting. What do I need to do inorder to accomplish this?
我曾尝试使用 Collections.sort() 方法,但结果不是我想要的。我需要做什么才能实现这一目标?
采纳答案by Yuval Adam
回答by Paul Tomblin
If you want the collection to remain sorted, rather than sorting it at specific points, you could put it in a TreeSet with a defined Comparator. Otherwise, I'd use the Collections.sort method already mentioned by Yuval.
如果您希望集合保持排序,而不是在特定点对其进行排序,则可以将其放入具有定义比较器的 TreeSet 中。否则,我会使用 Yuval 已经提到的 Collections.sort 方法。
回答by Pierre
public class Foo
implements Comparable<Foo>
{
private String aField;
public Foo(String s)
{
aField=s;
}
public String getAField()
{
return aField;
}
public int compareTo(Foo other)
{
return getAField().compareTo(other.getAField());
}
@Override
public String toString()
{
return getAField();
}
}
and then
进而
Collections.sort(list);
Collections.sort(list);
回答by Dan Dyer
Collections.sort(fooList,
new Comparator<Foo>()
{
public int compare(Foo f1, Foo f2)
{
return f1.toString().compareTo(f2.toString());
}
});
Assuming that toString never returns null and that there are no null items in the list.
假设 toString 从不返回 null 并且列表中没有 null 项。
回答by TofuBeer
I would strongly advise you to only use toString for debugging purposes... however... to expand on what Yuval A wrote above...
我强烈建议您仅将 toString 用于调试目的......但是......扩展Yuval A上面写的内容......
public class X implements Comparator { public int compare(final Foo a, final Foo b) { return (a.toString().compareTo(b.toString())); } }
However you really should have Foo implement Comarable or write a proper Compartor that does not make use of toString.
但是,您确实应该让 Foo 实现 Comarable 或编写一个不使用 toString 的正确比较器。
回答by psykotedy
I would do something very similar to Pierre:
我会做一些与皮埃尔非常相似的事情:
public class Foo implements Comparable<Foo>
{
private String aField;
@Override
public String toString()
{
return aField;
}
public int compareTo(Foo o)
{
return this.toString().compareTo(o.toString());
}
}
Then, like Pierre, I would use Collections.sort(list)
as Pierre suggests.
然后,像皮埃尔一样,我会Collections.sort(list)
按照皮埃尔的建议使用。
回答by Mario Fusco
lambdaj allows you to sort, filter and in general manipulate collections without writing loops or obscure inner classes. For example the sorting you were asking can be achieved as it follows:
lambdaj 允许您对集合进行排序、过滤和一般操作,而无需编写循环或模糊的内部类。例如,您要求的排序可以按如下方式实现:
sort(foos, on(Foo.class).toString());
If you are interested in it check it out at:
如果您对此感兴趣,请访问:
回答by Cowan
google-collectionsmakes this really easy with Ordering:
google-collections通过Ordering使这变得非常容易:
Collections.sort(list, Ordering.usingToString());
Is bringing in a whole 3rd-party library just to use something you could write trivially using a Comparator (as others have provided) worthwhile? No, but google-collections is so cool you'll want to have it anyway for a bunch of other reasons.
引入整个 3rd-party 库只是为了使用您可以使用 Comparator(如其他人提供的那样)轻松编写的东西值得吗?不,但是 google-collections 太酷了,你无论如何都会因为其他一些原因想要拥有它。
On the sorting front, you can also easily do things like reversing:
在排序方面,您还可以轻松执行诸如反转之类的操作:
Ordering.usingToString().reverse();
or break ties:
或打破关系:
Ordering.usingToString().compound(someOtherComparator);
or deal with nulls:
或处理空值:
Ordering.usingToString().nullsFirst();
etc., but there's a bunch more stuff in there (not just sorting-related, of course) that leads to really expressive code. Check it out!
等等,但是那里还有更多的东西(当然不仅仅是与排序相关的),它们会导致真正具有表现力的代码。一探究竟!
回答by David Leppik
The Java 8 version:
Java 8 版本:
list.sort(Comparator.comparing(Object::toString));
Or streaming:
或流媒体:
List<Foo> sortedList = unsortedList
.stream()
.sorted(Comparator.comparing(Object::toString)))
.collect(Collectors.toList());
回答by Pierre
Sort ArrayList on POJO int property (Ascending or Descending):
在 POJO int 属性(升序或降序)上对 ArrayList 进行排序:
Collections.sort(myPojoList, (a, b) -> a.getId() - b.getId()); //ASC
Collections.sort(myPojoList, (a, b) -> b.getId() - a.getId()); //DESC
//Alternatively use Integer.compare()
Collections.sort(myPojoList, (a, b) -> Integer.compare(a.getId(), b.getId())); //ASC
Collections.sort(myPojoList, (a, b) -> Integer.compare(b.getId(), a.getId())); //DESC
Sort ArrayList on POJO String property:
在 POJO String 属性上对 ArrayList 进行排序:
Collections.sort(myPojoList, (a, b) -> a.getName().compareTo(b.getName())); //ASC
Collections.sort(myPojoList, (a, b) -> b.getName().compareTo(a.getName())); //DESC
Sort ArrayList on POJO Boolean property:
在 POJO 布尔属性上对 ArrayList 进行排序:
Collections.sort(myPojoList, (a, b) -> Boolean.compare(a.isMale(), b.isMale())); //ASC
Collections.sort(myPojoList, (a, b) -> Boolean.compare(b.isMale(), a.isMale())); //DESC
Extra: get distinct ArrayList
额外:获取不同的 ArrayList
myPojoList= new ArrayList<>(new LinkedHashSet<>(myPojoList)); //Distinct