Let's say I have a list in which there are workers, each employee has 3 fields: his name, the department in which he works (there may be only the name of the department or an object from the class department) and his salary.
Elvis Software Engineering 1000 Samba Mechanical Engineering 2000 Bamba Industrial Engineering 3000 Bisli Medical Engineering 4000 Kinder Electrical Engineering 1000 Elvis Software Engineering 9999
Now I want to sort them by their names and put the result in the queue. and put the queue on the card, ordered from the bottom up so the result that I want after sorting:
Bamba Industrial Engineering 3000 Bisli Medical Engineering 4000 Elvis Software Engineering 1000 Elvis Software Engineering 9999 Samba Mechanical Engineering 2000 Kinder Electrical Engineering 1000
I am not allowed to use Collection.sort (), so I use a comparator that sorts workers by their names, if the name is equal - it is sorted by the department, if the department is equal - it is sorted by salary. here the comparator I wrote:
class WorkerComparatorByName implements Comparator<Worker<?>> { @Override public int compare(Worker<?> w1, Worker<?> w2) { int compareValue = w1.getName().compareTo(w2.getName()); if (compareValue != 0) return compareValue; compareValue = w1.getDepartment().toString().compareTo(w2.getDepartment().toString()); if (compareValue != 0) return compareValue; return w1.getSalary() - w2.getSalary(); } }
The problem is this:
Bamba Industrial Engineering 3000 Bisli Medical Engineering 4000 Elvis Software Engineering 1000 Samba Mechanical Engineering 2000 Kinder Electrical Engineering 1000 Elvis Software Engineering 9999
all workers are sorted, but Elvis (which is duplicated) is NOT sorted, he remains at the end of the queue. I tried replacing Elvis with another duplicate name and the same result. What am I missing? how can i sort the duplicate value so that they are one by one? Here is the code:
public <T extends Worker<?>> Map<?, ?> createMap(ArrayList<T> list) { int i = 1;
java sorting treemap queue comparator
Robert
source share