Search code examples
javacomparable

Want to sort an ArrayList of objects by several different attributes


I've got this class called Block (each Block has an x value and a y value). I've created a bunch of these and put them all in a list. I've managed to sort the list by x-value:

public class Block implements Comparable<Block> {
...
public int compareTo(Block block2){
    return this.x - block2.x;
}

But I want to be able to sort the list both by x and by y-value at my leisure. Is this doable somehow?


Solution

  • You can implement two Comparators:

    enum BlockSort implements Comparator<Block> {
        XSORT {
            @Override
            public int compare(Block b1, Block b2) {
                return b1.x - b2.x;
            }
        },
    
        YSORT {
            @Override
            public int compare(Block b1, Block b2) {
                return b1.y - b2.y;
            }
        }
    }
    

    Then pass the appropriate instance XSORT/YSORT as a second argument to the sort method. For example:

    Collections.sort(blockList, BlockSort.XSORT);
    

    Additionally, if by-x isn't the natural ordering of Block instances, it would likely be wiser to not make Blocks Comparable at all.