[英]Comparator using a String field of my class for comparison?
I have a list of objects of type A, and I have to order it for a field of A, which is of type String.我有一个 A 类型的对象列表,我必须为 A 的字段排序,它是 String 类型的。
public class A{
public String field1;
public Integer field2;
...
}
If I had to order for the int field would have done so:如果我必须订购 int 字段会这样做:
Collections.sort(listOfA, new Comparator<A>() {
public int compare(A p1, A p2) {
return p1.field2 - p2.field2);
}
});
But unfortunately need to order by the field of type String.但不幸的是需要按字符串类型的字段排序。
How can I do this?我怎样才能做到这一点?
public int compare(A p1, A p2) {
return p1.field2.compareTo( p2.field2) );
}
Alternatively your class could implement interface Comparable , like this或者你的类可以实现接口Comparable ,像这样
public class A implements Comparable<A> {
public String field1;
public Integer flied2;
public int compareTo(A o) {
return this.field1.compareTo(o.field1);
}
}
Which would allow you to这将使您能够
Collections.sort(listofA);
Which IMO is preferable/cleaner if A's are always sorted by field1.如果 A 总是按 field1 排序,则哪个 IMO 更可取/更清洁。
你可以使用 String compareTo
Old thread, nevertheless.尽管如此,旧线程。
With java 8, you now have lambdas:使用 Java 8,您现在拥有 lambda:
listOfA.sort((a,b) -> a.field1.compareTo(b.field1));
Also, if one had a getter for field1, which one probably should, you could also then do此外,如果一个人有一个用于 field1 的吸气剂,那一个可能应该,你也可以这样做
listOfA.sort(Comparator.comparing(A::getFieldOne));
If you don't have a getter, there's also this:如果你没有吸气剂,还有这个:
listOfA.sort(Comparator.comparing(a -> a.field1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.