user4150758
user4150758

Reputation: 453

How to write my own comparator class in java?

I didn't find proper solution for the below scenario. I have employee names and location. In each location many employees can work. Example: assume that employee names are unique so I consider it as a key and value as location.

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

Well my scenario is i have to write my own comparator where location is sorted first and when there are multiple locations of same name then they need to be sorted by employees. Any kind of help is appreciated.

Upvotes: 2

Views: 1887

Answers (3)

Igor Tyulkanov
Igor Tyulkanov

Reputation: 5548

You can use similar structure:

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

This is Multimap, and this is implementation by conventional means, but also there are third-party implementation, e.g. Guava. Guava has some sorted, synchronized and immutable implementations of multimaps, you can use them by default or to see how to do some things.

You can put values like below:

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

Upvotes: 0

you need a structure, and 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;
    }

}

Upvotes: 1

gerrytan
gerrytan

Reputation: 41123

The problem is in your data structure. TreeMap ensure your keys are always sorted in an order, but your key doesn't have full information you need to sort. Instead what you need is probably

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

where Employee is:

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

Now you can create a comparator for Employee

Upvotes: 1

Related Questions