I have a simple class Cell:
public class Cell {
private int row, column;
public Cell(int row, int column) {
this.row = row;
this.column = column;
}
public void setRow(int row) {
this.row = row;
}
public void setColumn(int column) {
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
@Override
public String toString() {
return "[" + row + "," + column + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + column;
result = prime * result + row;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cell other = (Cell) obj;
if (column != other.column)
return false;
if (row != other.row)
return false;
return true;
}
}
I have created a HashMap. Now, I want to sort it by value. This was my approach:
PriorityQueue<Entry<Cell, Integer>> sortedCells = new PriorityQueue<Map.Entry<Cell, Integer>>(cells.size(), new CompareByValue());
sortedCells.addAll(cells.entrySet());
and CompareByValue is a Comparator:
private class CompareByValue implements Comparator<Map.Entry<Cell, Integer>> {
@Override
public int compare(Entry<Cell, Integer> lhs,
Entry<Cell, Integer> rhs) {
return lhs.getValue().compareTo(rhs.getValue());
}
}
This entrySet
:
{[1,2]=1, [1,0]=2, [2,1]=1, [-1,0]=1, [-1,1]=1, [0,2]=1, [0,-1]=1}
returns this PriorityQueue
:
[[1,2]=1, [-1,0]=1, [2,1]=1, [1,0]=2, [-1,1]=1, [0,2]=1, [0,-1]=1]
Why it doesn't sort by value? I want something like:
[[1,0]=2, [1,2]=1, [-1,0]=1, [2,1]=1, [-1,1]=1, [0,2]=1, [0,-1]=1]
It's not my first time sorting a map by value using PriorityQueue
, but I don't understand what is going on here..