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

Answer by Richard H for How to sort List of objects by some property

$
0
0

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {    Collections.sort(roles, new Comparator() {        @Override        public int compare(Object o1, Object o2) {            int x1 = ((CompanyRole) o1).getBegin();            int x2 = ((CompanyRole) o2).getBegin();            if (x1 != x2) {                return x1 - x2;            } else {                int y1 = ((CompanyRole) o1).getEnd();                int y2 = ((CompanyRole) o2).getEnd();                return y2 - y1;            }        }    });}

Viewing all articles
Browse latest Browse all 19

Trending Articles



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