我有一个Class1
public class Class1 {
public Class(String s, int[] s1, int soc) {
this.s = s;
this.s1 = s1;
this.soc = soc
}
}
我有List
Class1
(List<Class1>
)。我想按soc
对此列表进行排序,以获得Class1
最高soc
的{{1}}
答案 0 :(得分:14)
使用比较器
Collections.sort(list, new Comparator<Class1>() {
public int compare(Class1 c1, Class1 c2) {
if (c1.soc > c2.soc) return -1;
if (c1.soc < c2.soc) return 1;
return 0;
}});
(注意,compare方法返回-1表示“第一个参数在排序列表中排在第一位”,0表示“它们是同等排序的”,1表示“第一个参数在排序列表中排在第二位”,并且list由sort方法修改
答案 1 :(得分:1)
这是一个完整的例子:
import java.util.*;
class Class1 {
String s;
int[] s1;
int soc;
public Class1(String s, int[] s1, int soc) {
this.s = s;
this.s1 = s1;
this.soc = soc;
}
public String toString() { return String.format("s: %s soc: %d", s, soc); }
}
public class Test {
public static void main(String... args) {
List<Class1> list = new ArrayList<Class1>();
list.add(new Class1("abcd", new int[] {1}, 3));
list.add(new Class1("efgh", new int[] {2}, 5));
list.add(new Class1("ijkl", new int[] {8}, 9));
list.add(new Class1("mnop", new int[] {3}, 7));
Collections.sort(list, new Comparator<Class1>() {
public int compare(Class1 o1, Class1 o2) {
return o1.soc > o2.soc ? -1 : o1.soc == o2.soc ? 0 : 1;
}
});
System.out.println(list.toString().replaceAll(",", "\n"));
}
}
它打印以下内容:
[s: ijkl soc: 9
s: mnop soc: 7
s: efgh soc: 5
s: abcd soc: 3]
答案 2 :(得分:0)
创建一个实现Comparator的类,创建自定义排序方法,然后将该类的实例传递给此函数:Collections.sort
答案 3 :(得分:0)
虽然Scott Stanchfield的答案通常是目前在Java中最简单的方法,但如果你有其他功能性的东西,你可能想要对你的类的属性做些什么,那么使用Guava的Function秒。
public class Class1 {
...
public static final Function<Class1, Integer> GET_SOC =
new Function<Class1, Integer>() {
public Integer apply(Class1 input) {
return input.soc;
}
};
...
}
然后您可以使用其Ordering类进行排序:
List<Class1> list = ...;
Collections.sort(list, Ordering.natural().reverse().onResultOf(Class1.GET_SOC));
这使用基于每个soc
实例的Class1
属性的自然顺序的反向来给出您想要的顺序。