java sort list of objects by specifiable attribute

前端 未结 4 2012
南方客
南方客 2020-12-07 03:58

I want to sort a List of objects by a specified attribute of those objects and I want to choose which attribute should be used for sorting. Example:

class          


        
4条回答
  •  鱼传尺愫
    2020-12-07 04:13

    It would be much simpler to use custom comparators:

    To sort by name:

    Arrays.sort(carArray, Comparator.comparing(Car::name));
    

    To sort by colour:

    Arrays.sort(carArray, Comparator.comparing(Car::colour));
    

    So you could modify getSortedArray():

    public static Car[] getSortedArray(Car[] carArray, Comparator comparator) {
        Car[] sorted = carArray.clone()
        Arrays.sort(sorted, comparator);
        return sorted;
    }
    

    And call it like this:

    Car[] sorted = getSortedArray(carArray, Comparator.comparing(Car::name));
    

    Edit:

    If you use a language version that does not support these features, you can create the comparators by explicitly creating a nested class that implements the Comparator interface.

    This, for example, is a singleton Comparator that compares Car instances by name:

    static enum ByName implements Comparator {
        INSTANCE;
    
        @Override
        public int compare(Car c1, Car c2) {
            return c1.name().compareTo(c2.name());
        }
    }
    

    Then call:

    Car[] sorted = getSortedArray(carArray, ByName.INSTANCE);
    

提交回复
热议问题