這個問題在這里已經有了答案: 如何使用 Java8 lambda 以相反的順序對流進行排序? (13 個回答) 10 小時前關閉。
我正在嘗試對存盤在 List 中的物件欄位值進行排序。
我找到了以下解決方案來比較字串,但如何比較字串值并進行相應排序?
我希望先對“Y”狀態值進行排序,然后再對“N”進行排序
class Student {
int rollno;
String name, status;
// Constructor
public Student(int rollno, String name,
String status) {
this.rollno = rollno;
this.name = name;
this.status = status;
}
public String getStatus() {
return status;
}
}
ArrayList < Student > ar = new ArrayList < Student > ();
ar.add(new Student(111, "bbbb", "Y"));
ar.add(new Student(131, "aaaa", "N"));
ar.add(new Student(121, "cccc", "Y"));
Collections.sort(ar, (a, b) - > a.getStatus().compareTo(b.getStatus()));
uj5u.com熱心網友回復:
如果我理解正確,您需要參考方法 getStatus() 其自然順序排序
ar.sort(Comparator.comparing(Student::getStatus));
如果需要逆序
ar.sort(Comparator.comparing(Student::getStatus).reversed());
uj5u.com熱心網友回復:
字串“Y”按字典順序出現在“N”之后,因此您需要顛倒默認順序。
有一些方法可以做到,一種是否定比較函式的結果:
Collections.sort(ar, (a, b) - > -a.getStatus().compareTo(b.getStatus());
另一個是改變運算元的順序:
Collections.sort(ar, (a, b) - > b.getStatus().compareTo(a.getStatus());
uj5u.com熱心網友回復:
為此,您需要一個比較器類,它將比較兩個學生,在這種情況下,如果您希望當學生的狀態為“Y”時,它會排在“N”之前,您將需要這樣的東西:
public static class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
// Compare the students, return -1 if o1 is "greater" than o2. Return 1 if o2 is "greater" than o1
if (o1.status.equals("Y")) return -1;
if (o2.status.equals("Y")) return 1;
return 0;
}
}
然后你可以這樣比較:
List<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "Y"));
ar.add(new Student(131, "aaaa", "N"));
ar.add(new Student(121, "cccc", "Y"));
Collections.sort(ar, new StudentComparator());
輸出 :
[Student{rollno=121, name='cccc', status='Y'}, Student{rollno=111, name='bbbb', status='Y'}, Student{rollno=131, name='aaaa', status='N'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403813.html
標籤:
下一篇:Spark:從輸出RDD中提取值
