Olá, gostaria de ordenar meu mapa pelo valor e não pela chave. Código:
package eConjuntos.map;
import java.text.Collator;
import java.util.Comparator;
import java.util.TreeMap;
public class TesteMap {
public static void main(String[] args) {
Letra l1 = new Letra();
l1.setDescricao("A");
Letra l2 = new Letra();
l2.setDescricao("B");
Letra l3 = new Letra();
l3.setDescricao("C");
TreeMap<String,Letra> mapa = new TreeMap(new LetraComparator());
mapa.put("C",l1);
mapa.put("B",l2);
mapa.put("A",l3);
System.out.println(mapa.toString());
}
}
class LetraComparator implements Comparator<String>{
public int compare(String p1, String p2){
return Collator.getInstance().compare(p2,p1);
}
}
class Letra {
private String descricao;
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((descricao == null) ? 0 : descricao.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Letra other = (Letra) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
return true;
}
public String toString(){
return this.descricao;
}
}
A saída é:
{C=A, B=B, A=C}
Gostaria que fosse:
{A=C, B=B, C=A}
O que preciso mudar neste código?