假设我有以下课程:

public class StatReport{
    private Integer id;
    private Date registrationDate;
    private Map<Currency, BigDecimal> accountMap;

    //Getters, Setters
}


我想编写一个方法,该方法根据我传递的参数对List进行排序。对于instacance:

public List<StatReport> sortStatReportList(List<StatReport> reports, String propertyName){
    //To sort the reports by propertyName's order.
}


Comparator<T>在这种情况下是否有帮助?如何以正确的方式实现该方法?

最佳答案

是的,可以使用Apache BeanComparator

public List<StatReport> sortStatReportList(List<StatReport> reports, String propertyName){
    List<StatReport> temp = new ArrayList<StatReport>(reports); //create a copy because Collections.sort sorts the given parameter
    Collections.sort(temp , new BeanComparator(propertyName));
    return temp;
}

08-07 02:32