如何在 java 中编写自己的比较器 class?

How to write my own comparator class in java?

我没有为以下情况找到合适的解决方案。我有员工姓名和位置。每个地点都有许多员工可以工作。 示例:假设员工姓名是唯一的,所以我将其视为键,将值视为位置。

TreeMap<String,String> t=new TreeMap<String,String>();
t.put(mike, Houston);
t.put(arian, Houston);
t.put(John, Atlanta);

好吧,我的方案是我必须编写自己的 comparator,其中首先对位置进行排序,当存在多个同名位置时,则需要按 employees 对它们进行排序。任何形式的帮助表示赞赏。

问题出在你的数据结构上。 TreeMap 确保您的键始终按顺序排序,但您的键没有您需要排序的完整信息。相反,您需要的可能是

TreeSet<Employee> employees = new TreeSet<>(employeeComparator);

员工所在的位置:

public class Employee {
   private String name;
   private String location;
   /* getters & setters omitted */
}

现在您可以为员工创建一个比较器

你需要一个结构,compareTo:

public class EmpLoc  implements Comparable<EmpLoc>  {
String employee;
String location;

public EmpLoc (String _employee, String _location)
    {
    employee=_employee;
    location=_location; 
    }


@Override
public int compareTo(EmpLoc other)
    {
    int last = this.location.compareTo(other.location);
    return last == 0 ? this.employee.compareTo(other.employee) : last;
    }

}

您可以使用类似的结构:

Map<String, List<String>> map = new TreeMap<>(<your_own_comparator_for_locations_or_default_one>);

这是Multimap, and this is implementation by conventional means, but also there are third-party implementation, e.g. Guava。 Guava 有一些排序的、同步的和不可变的多重映射实现,你可以默认使用它们或者看看如何做一些事情。

您可以输入如下值:

public void putEmployees(String location, String employee) {
    List<String> employees = map.get(location);
    if (employee == null) {
        employees = new ArrayList<>();
    }
    employees.add(employee);
    Collections.sort(employees, <your_own_comparator_for_employees_or_default_one>);
    map.put(location, employees);
}