How to use Comparator in Java to sort

后端 未结 14 1802
时光取名叫无心
时光取名叫无心 2020-11-22 02:19

I learned how to use the comparable but I\'m having difficulty with the Comparator. I am having a error in my code:

Exception in thread \"main\" java.lang.C         


        
14条回答
  •  无人及你
    2020-11-22 02:55

    There are a couple of awkward things with your example class:

    • it's called People while it has a price and info (more something for objects, not people);
    • when naming a class as a plural of something, it suggests it is an abstraction of more than one thing.

    Anyway, here's a demo of how to use a Comparator:

    public class ComparatorDemo {
    
        public static void main(String[] args) {
            List people = Arrays.asList(
                    new Person("Joe", 24),
                    new Person("Pete", 18),
                    new Person("Chris", 21)
            );
            Collections.sort(people, new LexicographicComparator());
            System.out.println(people);
            Collections.sort(people, new AgeComparator());
            System.out.println(people);
        }
    }
    
    class LexicographicComparator implements Comparator {
        @Override
        public int compare(Person a, Person b) {
            return a.name.compareToIgnoreCase(b.name);
        }
    }
    
    class AgeComparator implements Comparator {
        @Override
        public int compare(Person a, Person b) {
            return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
        }
    }
    
    class Person {
    
        String name;
        int age;
    
        Person(String n, int a) {
            name = n;
            age = a;
        }
    
        @Override
        public String toString() {
            return String.format("{name=%s, age=%d}", name, age);
        }
    }
    

    EDIT

    And an equivalent Java 8 demo would look like this:

    public class ComparatorDemo {
    
        public static void main(String[] args) {
            List people = Arrays.asList(
                    new Person("Joe", 24),
                    new Person("Pete", 18),
                    new Person("Chris", 21)
            );
            Collections.sort(people, (a, b) -> a.name.compareToIgnoreCase(b.name));
            System.out.println(people);
            Collections.sort(people, (a, b) -> a.age < b.age ? -1 : a.age == b.age ? 0 : 1);
            System.out.println(people);
        }
    }
    

提交回复
热议问题