【问题标题】:Ascending and Desending order in same program using java使用java在同一程序中的升序和降序
【发布时间】:2019-05-06 20:59:02
【问题描述】:

我想根据 id 和标记对对数据进行排序。 ID应该按升序排列,标记应该按降序排列,这是我的代码:

ArrayList<Student> al=new ArrayList<Student>();
    al.add(new Student(1,"dg",58));
    al.add(new Student(2,"dg",48));
    al.add(new Student(1,"dg",98));
    al.add(new Student(2,"dg",68));
    al.add(new Student(1,"dg",38));
    al.add(new Student(2,"dg",28));
    al.add(new Student(2,"dg",90));    

输出如下:

1 dg 98  
1 dg 58  
1 dg 38  
2 dg 90  
2 dg 68  
2 dg 48  
2 dg 28  

【问题讨论】:

  • 您可以使用Collections.sort(List, Comparator>)。根据您的需要实施比较器。
  • @AxelH 我使用过,但我只排序了 id 或标记,但我都想要
  • 这就是为什么你需要定义你的 Comparator 来正确比较这两个值。向我们展示实际的比较逻辑,以便我们帮助您完成 tt。
  • Collections.sort(al,(s1,s2)->{ return s1.ids2.marks?-1:s1.markss2.id?1:0;});我有错误
  • 我试试这个 Collections.sort(al,(s1,s2)->{ return s1.id>s2.id?s1.marks>s2.marks?-1:s1.markss2.marks?-1:s1.markss2.marks?-1: s1.marks

标签: java list sorting arraylist collections


【解决方案1】:

您必须为Student 类实现Comparable 或直接使用自定义Comparator 对其进行排序:

Comparator<Student> comparator = Comparator
    .comparing(Student::getId)                            // First ID in ascending order
    .thenComparing(Comparator.comparing(Student::getMark) // Then mark 
                             .reversed());                // ... but in descending order

al.sort(comparator);                                      // Here is the sort performed

【讨论】:

    【解决方案2】:

    试试这个

     Collections.sort(al,(s1,s2)->{
    
                return s1.id<s2.id?-1:s1.id>s2.id?1:s1.marks>s2.marks?-1:0;
            });
            al.forEach(p->{
                System.out.println(p);
            });
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2015-03-09
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多