Java - Sort - Variable comparator

后端 未结 2 1202
一个人的身影
一个人的身影 2021-01-29 05:37

I\'m trying to sort a list of Objects based upon user input. How can I go about having the sort method implement a variant comparator?

Example:

List<         


        
2条回答
  •  心在旅途
    2021-01-29 06:25

    This will helps you:

    String sortBy = "key";
    list.sort(Comparator.comparing(report -> {
        try {
            return (Comparable) report.getClass().getDeclaredField(sortBy).get(report);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("exception", e);
        }
    }));    
    

提交回复
热议问题