对结果末尾全 0 的数字列表进行排序

Suj*_*nil 6 java java-stream

我有人员名单,如果输入列表是3,0,2,7,0,8

我想要的输出是2,3,7,8,0,0

使用以下代码,我可以仅对非零数字进行排序以获取2,3,7,8输出。

sortedList = personList.stream()
                       .filter(Person -> Person.getAge()>0)
                       .sorted(Comparator.comparingInt(Person::getAge))
                       .collect(Collectors.toList());

zeroList=personList.stream()
                       .filter(Person -> Person.getAge()==0)
                       .collect(Collectors.toList());

sortedList.addAll(zeroList);
Run Code Online (Sandbox Code Playgroud)

上述两个语句可以合并为一个语句吗?

Sto*_*ica 6

您可以通过编写适当的比较器来确保零到达末尾:

sortedList = personList.stream()
   .sorted((p1, p2) -> {
      int a = p1.getAge();
      int b = p2.getAge();
      if (a == 0 && b == 0) return 0;
      if (a == 0) return 1;
      if (b == 0) return -1;
      return Integer.compare(a, b);
   })
   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

或者稍微更紧凑:

sortedList = personList.stream()
   .sorted((p1, p2) -> {
      int a = p1.getAge();
      int b = p2.getAge();
      return a == 0 || b == 0 ? Integer.compare(b, a) : Integer.compare(a, b);
   })
   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


azr*_*zro -2

您指定的过滤器.filter(Person -> Person.getAge()>0)不允许元素`等于0

您需要更改为:.filter(Person -> Person.getAge()>=0)

那么你需要指定一个更复杂的比较器

sortedlist = personList.stream()
            .filter(Person -> Person.getAge() >= 0)
            .sorted((o1, o2) -> {
                if (o1.getAge() == 0 || o2.getAge() == 0) 
                    return Integer.compare(o2.getAge(), o1.getAge());
                return Integer.compare(o1.getAge(), o2.getAge());
            })
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
  • 如果其中之一Person's age是,0它将以相反的方式进行比较(0 将是较大的数字 => 最后)
  • 如果没有任何年龄0:经典比较Integers