【问题标题】:How to write my own comparator class in java?如何在java中编写我自己的比较器类?
【发布时间】:2015-12-02 11:47:32
【问题描述】:

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

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

我的情况是我必须编写自己的comparator,其中位置首先排序,当有多个同名位置时,它们需要按employees 排序。任何形式的帮助表示赞赏。

【问题讨论】:

标签: java collections comparator treemap


【解决方案1】:

你需要一个结构,然后比较:

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;
    }

}

【讨论】:

    【解决方案2】:

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

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

    员工在哪里:

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

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

    【讨论】:

    • 甚至 TreeMap 也允许构造函数带有比较器 TreeMap employees = new TreeMap(employeeComparator);
    • @DheerendraKulkarni 映射需要两个类型参数:键和值。在这种情况下,所有信息都存储在 Employee 中,因此如果您使用映射,则没有将键映射到的值
    【解决方案3】:

    你可以使用类似的结构:

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

    这是Multimap,这是通过常规方式实现的,但也有第三方实现,例如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);
    }
    

    【讨论】:

    • 我不能给第三方。
    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2014-10-25
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多