我有 Java 排序的問題。在 SQL 中,我可以對每個欄位進行獨立排序。我在Java中需要類似的東西。
SELECT * FROM Stuff ORDER BY name ASC,last_name DSC;
使用時,sort(Comparator.comparing(Stuff::getName).thenComparing(Stuff::getLastName).reversed()我將整個排序反轉,我只希望第二個排序以相反的順序排列。有沒有它的庫,或者解決這個問題的簡單方法?
uj5u.com熱心網友回復:
有一個多載thenComparing()需要 aComparator所以你可以根據需要組合它們。其實thenComparing(function)只是一種方便的方法thenComparing(comparing(function))
因此你可以使用這個:
Comparator.comparing(Stuff::getName)
.thenComparing(Comparator.comparing(Stuff::getLastName).reversed())
這等于
Comparator<Stuff> nameAscComparator = Comparator.comparing(Stuff::getName);
Comparator<Stuff> lastNameDescComparator = Comparator.comparing(Stuff::getLastName).reversed();
Comparator<Stuff> combined = nameAscComparator.thenComparing(lastNameDescComparator);
uj5u.com熱心網友回復:
我總是有同樣的問題。所以我定義了三個輔助方法(orderBy和asc)desc來簡單地描述比較器。
@SafeVarargs
public static <T> Comparator<T> orderBy(Comparator<T> first, Comparator<? super T>... rest) {
for (Comparator<? super T> e : rest)
first = first.thenComparing(e);
return first;
}
public static <T, U extends Comparable<? super U>> Comparator<T> asc(Function<? super T, ? extends U> f) {
return Comparator.comparing(f);
}
public static <T, U extends Comparable<? super U>> Comparator<T> desc(Function<? super T, ? extends U> f) {
return Collections.reverseOrder(Comparator.comparing(f));
}
這是一個示例用法:
public static void main(String[] args) {
List<Stuff> list = Arrays.asList(
new Stuff("A", "a"),
new Stuff("B", "b"),
new Stuff("A", "c"));
list.sort(orderBy(asc(Stuff::getName), desc(Stuff::getLastName)));
list.forEach(System.out::println);
}
輸出:
Stuff [name=A, lastName=c]
Stuff [name=A, lastName=a]
Stuff [name=B, lastName=b]
如果你想按單個屬性排序,你也可以做類似list.sort(desc(Stuff::getLastName))without orderBy().
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530316.html
標籤:爪哇sql排序
上一篇:我想要一個按空格進行分詞的查詢
