使用lambda和自定义comparator类的java排序列表不起作用

inn6fuwd  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(468)

我试图用lambda和自定义比较器类“virussorter”对按名称排序的对象列表进行排序,但它什么也没做,我不知道为什么是主代码

  1. List<Virus> tmpVir = new ArrayList<>(OuterClass.getSvi_virusi());
  2. tmpVir.stream()
  3. .sorted(new VirusSorter())
  4. .forEach(System.out::println);

比较器等级:

  1. class VirusSorter implements Comparator<Virus> {
  2. @Override
  3. public int compare(Virus o1, Virus o2) {
  4. if(o1.getNaziv().compareTo(o2.getNaziv().toUpperCase()) == 1)
  5. {
  6. return 1;
  7. }
  8. else if(o1.getNaziv().compareTo(o2.getNaziv().toUpperCase()) == -1)
  9. {
  10. return -1;
  11. }
  12. else
  13. return 0;
  14. }
  15. }
mklgxw1f

mklgxw1f1#

比较输入为 o2.getNaziv().toUpperCase() 以及 o1.getNaziv() (没有一个使其大写的调用),所以它永远不会比较like和like。
试试这样的

  1. public int compare(Virus o1, Virus o2) {
  2. return o1.getNaziv().compareToIgnoreCase(o2.getNaziv());
  3. }

相关问题