Skip to content

Instantly share code, notes, and snippets.

@alexrios
Last active December 11, 2015 02:18
Show Gist options
  • Save alexrios/4529637 to your computer and use it in GitHub Desktop.
Save alexrios/4529637 to your computer and use it in GitHub Desktop.
Java "order by" made easy
//Smart use of enums
public enum DeviceComparator implements Comparator<Device> {
 
    ID {
        public int compare(Device o1, Device o2) {
            return Integer.valueOf(o1.getId()).compareTo(o2.getId());
        }},
    NAME {
        public int compare(Device o1, Device o2) {
            return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
        }};
 
    public static Comparator<Device> descending(final Comparator<Device> other) {
        return new Comparator<Device>() {
            public int compare(Device o1, Device o2) {
                return -1 * other.compare(o1, o2);
            }
        };
    }
 
    public static Comparator<Device> getComparator(final DeviceComparator... multipleOptions) {
        return new Comparator<Device>() {
            public int compare(Device o1, Device o2) {
                for (DeviceComparator option : multipleOptions) {
                    int result = option.compare(o1, o2);
                    if (result != 0) {
                        return result;
                    }
                }
                return 0;
            }
        };
    }
 
}
 
// just call
//devices = List<Device> {...} 
Collections.sort(devices, descending(getComparator(ID, NAME)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment