How to sort by a field of class with its own comparator?

三世轮回 提交于 2021-01-21 10:31:35

问题


I have a sample class, say Country:

class Country {
    public String name;
    public int population;
    public Flag flag;  
    ...                                                                        
}

I have this Flag class defined somewhere else

class Flag {
    String id;
    int pixel;
    ...
}

Now I create a separate comparator DefaultFlagRankingComparator() that can sort Flag by id. How can I sort a list of Country by Flag id, using this DefaultFlagRankingComparator()?


回答1:


You can invoke the compare method of the Comparator with the flag field of each country.

DefaultFlagRankingComparator flagComparator =
        new DefaultFlagRankingComparator();
Collections.sort(countries, (a, b) ->
        flagComparator.compare(a.getFlag(), b.getFlag()));

You could also use Comparator.comparing to create a Comparator using a key extracting function and a Comparator that compares those keys (as suggested by Louis Wasserman).

DefaultFlagRankingComparator flagComparator =
        new DefaultFlagRankingComparator();
Collections.sort(countries,
        Comparator.comparing(Country::getFlag, flagComparator));



回答2:


  1. You can compare String values of ids using predefined methods:

    Arrays.sort(countries, (c1, c2) -> Objects.compare(
            c1.getFlag().getId(), c2.getFlag().getId(),
            Comparator.naturalOrder()));
    
    Arrays.sort(countries, Comparator.comparing(country ->
            country.getFlag().getId(), Comparator.naturalOrder()));
    
  2. You can specify a custom Comparator:

    Arrays.sort(countries, Comparator
            .comparing(country -> country.getFlag(),
                    new DefaultFlagRankingComparator()));
    
    static class DefaultFlagRankingComparator implements Comparator<Flag> {
        @Override
        public int compare(Flag o1, Flag o2) {
            return Objects.compare(o1.getId(), o2.getId(),
                    Comparator.naturalOrder());
        }
    }
    
  3. You can implement interface Comparable in the Flag class:

    Arrays.sort(countries, Comparator.comparing(Country::getFlag));
    
    static class Flag implements Comparable<Flag> {
        String id;
    
        public String getId() { return id; }
    
        @Override
        public int compareTo(Flag that) {
            return Objects.compare(this.getId(), that.getId(),
                    Comparator.naturalOrder());
        }
    }
    


来源:https://stackoverflow.com/questions/65485183/how-to-sort-by-a-field-of-class-with-its-own-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!