简体   繁体   English

您如何为特定字符串编写自定义 Java 比较器?

[英]How Do You Write A Custom Java Comparator For A Specific String?

Hello I was wondering if somebody could help me with a little bit of code I'm stuck on.您好,我想知道是否有人可以帮助我编写一些我坚持的代码。 So I'm writing a custom comparator using lambda statements I want to do the following.所以我正在使用 lambda 语句编写一个自定义比较器,我想做以下事情。 If the names that return of.getName() equals to each other then I want to pick the one that is the String "Up" from.getDirection() (Its guaranteed one of them is "Up" in that case, the other is "Down"), else we will look at which one is alphabetically higher depending on the.getType().如果返回 of.getName() 的名称彼此相等,那么我想从 .getDirection() 中选择字符串“Up”的名称(在这种情况下,它保证其中一个是“Up”,另一个是"Down"),否则我们将根据.getType() 来查看哪个字母顺序更高。

So far I have this: (x,y) -> x.getName().equals(y.getName())? //confused part: x.getType().compareTo(y.getType) );到目前为止,我有这个: (x,y) -> x.getName().equals(y.getName())? //confused part: x.getType().compareTo(y.getType) ); (x,y) -> x.getName().equals(y.getName())? //confused part: x.getType().compareTo(y.getType) );

Any help would be appreciated, thank you.任何帮助将不胜感激,谢谢。

I created an example class, hope it can help.我创建了一个示例 class,希望对您有所帮助。

package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @author jinleizhang
 */
public class ComparatorTest {
  static class Car {
    String name;
    boolean up;
    String type;

    Car(String name, boolean up, String type) {
      this.name = name;
      this.up = up;
      this.type = type;
    }

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

    public boolean isUp() {
      return this.up;
    }

    public String getType() {
      return this.type;
    }

    @Override
    public String toString() {
      return "Car{" +
          "name='" + name + '\'' +
          ", up=" + up +
          ", type='" + type + '\'' +
          '}';
    }
  }

  public static void main(String[] args) {
    Car carA = new Car("NewCar", false, "type2020");
    Car carB = new Car("NewCar", true, "type2019");
    Car carC = new Car("OldCar", true, "type1990");

    List<Car> cars = new ArrayList<>();
    cars.add(carA);
    cars.add(carB);
    cars.add(carC);
    Collections.sort(cars, (x, y) -> {
      if (x.getName().equals(y.getName())) {
        return x.isUp() ? -1 : 1;
      }

      return x.getType().compareTo(y.getType());
    });

    for (var car : cars) {
      System.out.println(car);
    }
  }
}

output output

Car{name='OldCar', up=true, type='type1990'}
Car{name='NewCar', up=true, type='type2019'}
Car{name='NewCar', up=false, type='type2020'}

Don't try to get too greedy with terseness.不要试图对简洁过于贪婪。 Closures are nice, but the objective is not to write the least amount of code, it's to write only the code that's needed to get the job done in a way that's easily understood (well, most of the time anyway...)闭包很好,但目标不是编写最少的代码,而是只编写以易于理解的方式完成工作所需的代码(好吧,无论如何大部分时间......)

(x, y) -> {
    if (x.getName().equals(y.getName()) {
        return "Up".equals(x.getDirection()) ? -1 : 1;
    } else {
        return x.getType().compareTo(y.getType());
    }
}

You cannot write this as a comparator.你不能把它写成比较器。

Suppose you have these objects:假设你有这些对象:

  • A1: Name: A Direction: Down Type: 1 A1:名称:A 方向:向下 类型:1
  • A3: Name: A Direction: Up Type: 3 A3:名称:A 方向:向上 类型:3
  • B2: Name: B Direction: Up Type: 2 B2:名称:B 方向:向上 类型:2

According to your logic, A1 < B2 and B2 < A3 and A3 < A1.根据您的逻辑,A1 < B2 和 B2 < A3 和 A3 < A1。 This is a violation of the transitive property of the general contract of comparator.这违反了比较器一般契约的传递性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM