Java - Sort - Variable comparator

后端 未结 2 1199
一个人的身影
一个人的身影 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: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> (even if all getters will return Comparable objects, X will vary)

    Map> 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)));
    

提交回复
热议问题