Java - Sort - Variable comparator

后端 未结 2 1200
一个人的身影
一个人的身影 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);
        }
    }));    
    
    0 讨论(0)
  • 2021-01-29 06:27

    If all "keys" will be linked to getter methods, you can have a static mapping of key/getter that you use in a function:

    Note: we'll have to use raw type Comparable as we can't use different Functions<S3ObjectSummary, Comparable<T>> (even if all getters will return Comparable<X> objects, X will vary)

    Map<String, Function<S3ObjectSummary, Comparable>> map = new HashMap<>();
    map.put("key", s3 -> s3.getKey());
    map.put("modified", s3 -> s3.getModified());
    // other entries
    

    Then sort using:

    objectSummaryList.sort(Comparator.comparing(map.get(compareByKey)));
    
    0 讨论(0)
提交回复
热议问题