Java sorts List, supporting forward and reverse order

Share how to sort List in Java, supporting forward and reverse order.

1. Background : If you want to support both forward and reverse sorting methods, you can use Collections.sort()the or List.sort() method and pass in a custom comparator.

2. The example code is as follows :

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

List<FRowData> dataList = ...;  // 假设这是你的 FRowData 列表

// 正序排序
Collections.sort(dataList, Comparator.comparing(FRowData::getCode));

// 或者使用 dataList.sort(Comparator.comparing(FRowData::getCode));

// 输出正序排序结果
System.out.println("正序排序结果:");
for (FRowData rowData : dataList) {
    System.out.println(rowData.getCode());
}

// 倒序排序
Collections.sort(dataList, Comparator.comparing(FRowData::getCode).reversed());

// 或者使用 dataList.sort(Comparator.comparing(FRowData::getCode).reversed());

// 输出倒序排序结果
System.out.println("倒序排序结果:");
for (FRowData rowData : dataList) {
    System.out.println(rowData.getCode());
}

3. Code explanation : In the above example, we first use Comparator.comparing()the method to create a comparator to compare based on FRowDatathe object's fields. codeThen, we can choose to use Collections.sort()the method or List.sort()method to perform the sorting operation. For reverse sorting, we use .reversed()the method to reverse the sort order.

Guess you like

Origin blog.csdn.net/JonTang/article/details/131556626