【问题标题】:Using comparator with multiple comparators使用带有多个比较器的比较器
【发布时间】:2019-01-13 08:39:52
【问题描述】:

我可以使用此代码中的所有简单比较器进行排序,但不能使用ComplexComparator。我无法弄清楚如何编码以使其正常工作。任何建议/解释将不胜感激。

这是我的主程序:

package pkgTest;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Student[] students = new Student[6];
        students[0] = new Student("Pete", 1989, 3.6);
        students[1] = new Student("Tomas", 1989, 3.9);
        students[2] = new Student("Helen", 1990, 3.6);
        students[3] = new Student("Steve", 1991, 3.7);
        students[4] = new Student("Natalie", 1993, 3.7);
        students[5] = new Student("John", 1992, 4.0);

        NameComparator byName
                = new NameComparator();
        BirthDateComparator byBirthDate
                = new BirthDateComparator();
        AverageComparator byAverage
                = new AverageComparator();

        ComplexComparator complexSorting
                = new ComplexComparator(byName,
                        byAverage);

        System.out.println("===============");
        System.out.println("Before sorting:");
        System.out.println("===============");
        for (Student student : students) {
            System.out.println(student.getName()
                    + " // " + student.getBirthDate()
                    + " // " + student.getAverage());
        }

        Arrays.sort(students, complexSorting);

        System.out.println("==============");
        System.out.println("After sorting:");
        System.out.println("==============");
        for (Student student : students) {
            System.out.println(student.getName()
                    + " // " + student.getBirthDate()
                    + " // " + student.getAverage());
        }
    }
}

以下是其余的课程:

package pkgTest;

public class Student {

    private String name;
    private int birthDate;
    private double average;

    public Student(String name, int birthDate,
            double average) {
        this.name = name;
        this.birthDate = birthDate;
        this.average = average;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBirthDate() {
        return this.birthDate;
    }

    public void setBirthDate(int birthDate) {
        this.birthDate = birthDate;
    }

    public double getAverage() {
        return this.average;
    }

    public void setAverage(double average) {
        this.average = average;
    }
}


package pkgTest;

import java.util.Comparator;

public class ComplexComparator implements Comparator<Student> {

    public ComplexComparator(Comparator<Student> one,
            Comparator<Student> another) {
    }

    @Override
    public int compare(Student one, Student another) {
        /*This is the part that
        I just couldn't figure
        it out to get it work.

        It has to work no matter
        which 2 of the 3 comparators
        I use to set the input
        parameters of ComplexComparator.

        I have to make it work by
        modifying only this part of
        the code.*/
    }
}


package pkgTest;

import java.util.Comparator;

public class AverageComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        if (one.getAverage()
                < another.getAverage()) {
            return -1;
        } else if (one.getAverage()
                == another.getAverage()) {
            return 0;
        } else {
            return +1;
        }
    }
}

package pkgTest;

import java.util.Comparator;

public class BirthDateComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        if (one.getBirthDate()
                < another.getBirthDate()) {
            return -1;
        } else if (one.getBirthDate()
                == another.getBirthDate()) {
            return 0;
        } else {
            return +1;
        }
    }
}


package pkgTest;

import java.util.Comparator;

public class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        return one.getName().
                compareToIgnoreCase(another.getName());
    }
}

【问题讨论】:

  • 您将需要修改代码的其他部分。其他方式真的没有任何意义。
  • 你不应该实现一个复杂的比较(比如:如果名字相同,那么比较生日,如果相等,那么比较平均值)而不是在那里使用其他Comparators?跨度>
  • 不幸的是,这不取决于我,这是必须以这种方式完成的任务。否则我不会寻求帮助。
  • 你在重新发明轮子,但无论如何。您的复杂比较器应该遍历比较器并一个接一个地调用它们。只要一个比较不为 0,就返回它的结果。否则转到下一个。注意 Integer 和 Double 有一个 compare() 方法。
  • @JBNizet 是的,但即便如此,他也必须存储比较器,这必须在 compare 方法的代码之外完成,他声称这是他唯一被允许编辑的地方。

标签: java arrays sorting compare comparator


【解决方案1】:

如下修改您的 ComplexComparator

public class ComplexComparator implements Comparator<Student> {

private List<Comparator<Student>> listComparators;

     @SafeVarargs
    public ComplexComparator(Comparator<Student>... comparators) {
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Student studen1, Student studen2) {
        for (Comparator<Student> comparator : listComparators) {
            int result = comparator.compare(studen1, studen2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}

【讨论】:

    【解决方案2】:

    我不确定您希望如何呈现解决方案。但是根据我的理解,如果你只想把代码放在注释的地方,你可以试试这样放代码。

    假设比较名字后的情况,如果相同,你打算移动到平均。

    public int compare(Student StOne, Student StAnother) {
         if(one.compare(Sone, Sanother)==0) {
             return another.compare(StOne, StAnother);
             }
         else 
             return one.compare(StOne, StAnother);
         }
    

    但是为此,你需要确保你在ComplexComparator的构造函数中取的值(byName,byAverage)应该是类的实例变量,并且需要在构造函数中进行初始化。

    public class ComplexComparator implements Comparator<Student> {
    
     private Comparator<Student> one; 
     private Comparator<Student> another;
     public ComplexComparator(Comparator<Student> one,
            Comparator<Student> another) {
         this.one=one;
         this.another=another;
    }
    
    @Override
    public int compare(Student one, Student another) {
        //code given above
    } }
    

    【讨论】:

    • 我无法编译这个,缺少返回值。也找不到符号,方法 compare(Student,Student)
    • 尝试使用这个: public int compare(Student StOne, Student StAnother) { if(one.compare(Sone, Sanother)==0) { return another.compare(StOne, StAnother); }else return one.compare(StOne, StAnother); }
    • @sasieightynine 现在检查编辑的代码。它现在可以正常工作了。
    【解决方案3】:

    你将不得不像下面这样修改ComplexComparator类,至少......

    import java.util.Comparator;
    
    public class ComplexComparator implements Comparator<Student> {
    
        private Comparator<Student> comparatorOne;
        private Comparator<Student> comparatorTwo;
    
        public ComplexComparator(Comparator<Student> one,
                Comparator<Student> another) {
            this.comparatorOne = one;
            this.comparatorTwo = another;
        }
    
        @Override
        public int compare(Student one, Student another) {
            // make a first comparison using comparator one
            int comparisonByOne = comparatorOne.compare(one, another);
    
            // check if it was 0 (items equal in that attribute)
            if (comparisonByOne == 0) {
                // if yes, return the result of the next comparison
                return comparatorTwo.compare(one, another);
            } else {
                // otherwise return the result of the first comparison
                return comparisonByOne;
            }
        }
    }
    

    对于两个以上的Comparators,您需要一个List(或另一个重载的构造函数)和一个保持一定比较顺序的循环。

    编辑

    对于您对排序订单的额外要求,这可能会有所帮助:

        public class ComplexComparator implements Comparator<Student> {
    
        private Comparator<Student> comparatorOne;
        private Comparator<Student> comparatorTwo;
        private boolean orderOneAscending = true;
        private boolean orderTwoAscending = true;
    
        /**
         * Constructor without any sort orders
         * @param one   a comparator
         * @param another   another comparator
         */
        public ComplexComparator(Comparator<Student> one, Comparator<Student> another) {
            this.comparatorOne = one;
            this.comparatorTwo = another;
        }
    
        /**
         * Constructor that provides the possibility of setting sort orders 
         * @param one   a comparator
         * @param orderOneAscending sort order for comparator one 
         *      (true = ascending, false = descending)
         * @param another   another comparator
         * @param orderTwoAscending sort order for comparator two
         *      (true = ascending, false = descending)
         */
        public ComplexComparator(Comparator<Student> one, boolean orderOneAscending,
                Comparator<Student> another, boolean orderTwoAscending) {
            this.comparatorOne = one;
            this.comparatorTwo = another;
            this.orderOneAscending = orderOneAscending;
            this.orderTwoAscending = orderTwoAscending;
        }
    
        @Override
        public int compare(Student one, Student another) {
            int comparisonByOne;
            int comparisonByAnother;
    
            if (orderOneAscending) {
                /*  note that your lexicographical comparison in NameComparator 
                    returns a negative integer if the String is greater!
                    If you take two numerical Comparators, the order will
                    turn into the opposite direction! */
                comparisonByOne = comparatorOne.compare(another, one);
            } else {
                comparisonByOne = comparatorOne.compare(one, another);
            }
    
            if (orderTwoAscending) {
                comparisonByAnother = comparatorTwo.compare(one, another);
            } else {
                comparisonByAnother = comparatorTwo.compare(another, one);
            }
    
            if (comparisonByOne == 0) {
                return comparisonByAnother;
            } else {
                return comparisonByOne;
            }
        }
    }
    

    只需使用这些值并尝试一些修改以熟悉有关比较和排序的常见问题。 我希望这会有所帮助...

    【讨论】:

    • 有效!是否可以为每个比较器添加另外两个布尔类型输入参数,以便能够将排序类型设置为升序或降序?
    • “boolean类型输入参数”是什么意思?您可以在调用构造函数ComplexComparator(Comparator&lt;Student&gt; one, Comparator&lt;Student&gt; another) 时更改Comparators 的顺序。
    • public ComplexComparator(Comparator&lt;Student&gt; one, boolean ascending1, Comparator&lt;Student&gt; another, boolean ascending2) { this.one = .....}
    • 如果我将一个开关设置为 true 而另一个开关设置为 false 来运行排序,那么它将产生一个升序排序,而另一个降序排序。例如,名称按升序排列,而平均值按降序排列。无论我是否更改输入布尔参数,我都可以在升序和降序之间切换。
    • 所以基本上在类中添加两个布尔类型的变量,并重写比较方法以在返回值时检查布尔值。有可能吗?
    【解决方案4】:

    这是一个通用的复杂比较器,可用于任何类型的对象(基于this answer):

    public class ComplexComparator<T> implements Comparator<T> {
    
        private List<Comparator<T>> listComparators;
    
        @SafeVarargs
        public ComplexComparator(Comparator<T>... comparators) {
            listComparators = Arrays.asList(comparators);
        }
    
        @Override
        public int compare(T o1, T o2) {
            for (Comparator<T> comparator : listComparators) {
                int result = comparator.compare(o1, o2);
                if (result != 0) {
                    return result;
                }
            }
            return 0;
        }
    }
    

    当你使用它时会有一个未经检查的强制转换警告,但你可以禁止它,因为只要你的类具有可比性,它就会成功强制转换。

    @SuppressWarnings("unchecked")
    Comparator<MyClass> comparator = new ComplexComparator(
            MyClass.ComparatorA,
            MyClass.ComparatorB);
    
    Collections.sort(mySet, comparator);
    

    如果有人知道如何不收到该警告,请发表评论,我会更新答案。

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多