【问题标题】:Sort an ArrayList using Comparator Interface [closed]使用比较器接口对 ArrayList 进行排序
【发布时间】:2020-05-17 18:32:42
【问题描述】:

我没有通过使用比较器获得排序列表。我尝试使用 Collections.sort() 来解决它,然后只有我得到了正确的答案。

public class CompratorProgram2 {
    public static void main(String[] args) {

        List<Integer> l= new ArrayList<>();
            l.add(232);
            l.add(524);
            l.add(111);
            l.add(433);

Comparator<Integer> ac= new CompratorProgram();

            Collections.sort(l, ac);
       // Collections.sort(l);

        for(int i: l)
            System.out.println(i);
    }
}

二等

public class CompratorProgram implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2){
        if(o1>02)
            return 1;
        else
 return -1;
    }
}

【问题讨论】:

  • 我将其作为输出 - 232、524、111、433
  • 这是o2,而不是02
  • compare 方法违反了它的contract实现者必须确保所有xysgn(compare(x, y)) == -sgn(compare(y, x)) 当@ 987654330@ 和 y 相等,因为 compare(x, y)compare(y, x) 都会返回 -1

标签: java arraylist collections comparator


【解决方案1】:

您可以使用 java 版本 8 功能 lambda 表达式。所以不需要集合 List 具有接受 Comparator 的 sort() 方法。

  public static void main(String[] args) {
    List<Integer> integerList = new ArrayList<>();
    integerList.add(3333);
    integerList.add(3);
    integerList.add(55);
    integerList.add(2);

    integerList.sort((i1, i2) -> i1.compareTo(i2));

    System.out.println(integerList);
}

输出将是: [2、3、55、3333]

【讨论】:

  • 不需要像(i1, i2) -&gt; i1.compareTo(i2)这样指定比较器。您可以只使用integerList.sort(Comparator.naturalOrder()) 甚至integerList.sort(null)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多