【发布时间】:2015-12-04 03:06:23
【问题描述】:
我正在努力按对象属性的顺序对数组进行排序。我知道如何按顺序对数字进行排序,但我不知道如何对对象进行排序。例如,假设对象 A 的位置属性为 1,对象 B 的位置属性为 2。这些对象位于数组中。我怎样才能根据这个属性对它们进行排序?
谢谢
【问题讨论】:
我正在努力按对象属性的顺序对数组进行排序。我知道如何按顺序对数字进行排序,但我不知道如何对对象进行排序。例如,假设对象 A 的位置属性为 1,对象 B 的位置属性为 2。这些对象位于数组中。我怎样才能根据这个属性对它们进行排序?
谢谢
【问题讨论】:
你有类似的东西:
public class ExampleObject {
public int position;
}
然后,只需使用Comparator。
public static void main(String args[]) {
//example numbers
final Random r = new Random();
final List<ExampleObject> arrList = new ArrayList<>(100);
for (int i = 0; i < 100; i++) {
ExampleObject obj = new ExampleObject();
obj.position = r.nextInt(1000);
arrList.add(obj);
}
//comparator (as a lambda)
Collections.sort(arrList, (a, b) -> {
return a.position - b.position;
});
//output result
for (ExampleObject obj : arrList) {
System.out.println(obj.position);
}
}
另外,如果您必须对数组而不是List 进行排序,您也可以像这样使用Arrays.sort() 和Comparator。
【讨论】:
您可以通过在您的类中实现Comparable 接口来进行比较,如下所示。
public class Applcation {
public static void main(String[] args) {
A ary[] = {new A("D", 1),new A("C", 7),new A("K", 4),new A("L", 8),new A("S", 3)};
Arrays.sort(ary);
for (A a : ary) {
System.out.println(a.id+" - "+a.name);
}
}
}
class A implements Comparable<A>{
String name;
int id;
public A(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(A a) {
return this.id-a.id;
}
}
或者作为替代方案,您可以使用 java 8 流对数组进行排序,而无需实现 Comparable:
Arrays.stream(ary).sorted((a1,a2)->Integer.compare(a1.id, a2.id)).forEach(e->System.out.println(e.id+" - "+e.name));
输出:
1 - D
3 - S
4 - K
7 - C
8 - L
【讨论】: