有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java列表按字母顺序排序

一切都很好,但我想在排序顺序locationName,locationMasterList有整数,字符串和双对象。。 下面是我的代码

List<LocationMaster> locationMasterList = locationMasterService.findByProperty("locationId", locationId);


for (int n = 0; n < locationMasterList.size(); n++) {
    YearwiseBudget yearwiseBudget1 = new YearwiseBudget();
    String locationName = locationMasterList.get(n).getLocationNameE();
    Integer distId = locationMasterList.get(n).getLocationId();
    yearwiseBudget1.setRecordId(recordId.longValue());
    yearwiseBudget1.setAllocation(allocation);
    yearwiseBudget1.setExpenditure(expenditure);
    yearwiseBudget1.setLocationName(locationName);
    yearwiseBudget1.setAllocGen(allocGen);
    yearwiseBudget1.setAllocSC(allocSC);
    yearwiseBudget1.setAllocST(allocST);
    yearwiseBudget1.setExpGen(expGen);
    yearwiseBudget1.setExpSC(expSC);
    yearwiseBudget1.setExpST(expST);
    yearwiseBudget1.setDistrictId(distId);
    YearwiseBudgetList2.add(yearwiseBudget1);
}

共 (1) 个答案

  1. # 1 楼答案

    使YearlyBudget实现Comparable并在locationName成员上进行比较

    public class YearwiseBudget implements Comparable<YearwiseBudget> {
        private String locationName;
        .
        .
        .
    
        @Override
        public int compareTo(YearwiseBudget other) {
            return other.locationName.compareTo(locationName);
        }
    
    }
    

    然后在列表中使用Collections.sort(List<T> list)