java sort list of objects by specifiable attribute

前端 未结 4 2016
南方客
南方客 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:24

    TL;DR: There's already a wheel for that.

    I would say the easiest way to do this is to create a comparator:

    final Comparator byName = Comparator.comparing(Car::name);
    final Comparator byColour = Comparator.comparing(Car::colour);
    

    Then just use the appropriate method on Arrays to sort by a comparator:

    Arrays.sort(carArray, byName);
    

    Now you want to do it with an enum? Just have the enum implements Comparator:

    enum SortBy implements Comparator {
        NAME(Comparator.comparing(Car::name)),
        COLOUR(Comparator.comparing(Car::colour));
    
        private final Comparator delegate;
    
        private SortBy(Comparator delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public int compare(final Car o1, final Car o2) {
            return delegate.compare(o1, o2);
        }               
    }
    

    Want to sort by name then by colour? Easy:

    final Comparator byName = SortBy.NAME.thenComparing(SortBy.COLOUR);
    

    Want to sort by name in reverse order? Easy:

    final Comparator byName = SortBy.NAME.reversed();
    

提交回复
热议问题