Quantcast
Channel: How to sort List of objects by some property - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by jmj for How to sort List of objects by some property

$
0
0

Using Comparator

For Example:

class Score {    private String name;    private List<Integer> scores;    // +accessor methods}

    Collections.sort(scores, new Comparator<Score>() {        public int compare(Score o1, Score o2) {            // compare two instance of `Score` and return `int` as result.            return o2.getScores().get(0).compareTo(o1.getScores().get(0));        }    });

With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.

Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });

Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>