我想基于对象属性并使用Comparable对LinkedHashMap进行排序。这是我的代码:
public class MapClass{
public static void main(String args[]){
sortMapBasedOnValueObjectUsingComprable();
}
public static void sortMapBasedOnValueObjectUsingComprable(){
Map map = new LinkedHashMap();
map.put("2",new Pojo("456"));
map.put("4",new Pojo("366"));
map.put("1",new Pojo("466"));
map.put("8",new Pojo("5666"));
map.put("9",new Pojo("456"));
map.put("3",new Pojo("66"));
// How to sort ...?
Set<Map.Entry<String,Object>> st = map.entrySet();
Iterator itr = st.iterator();
while(itr.hasNext()){
Map.Entry mxt= (Map.Entry)itr.next();
Pojo pj = (Pojo)mxt.getValue();
System.out.println(pj.getX());
}
}
public class Pojo implements Serializable, Comparable<Object>{
private static final long serialVersionUID = 1L;
private String x;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public Pojo(String x) {
super();
this.x = x;
}
@Override
public int compareTo(Object o) {
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.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;
Pojo other = (Pojo) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
return true;
}
}
答案 0 :(得分:0)
所以你需要首先将你的entrySet转储到List中,然后对它进行排序。除非你使用TreeSet,否则你不能对一个集合进行排序。我更愿意将它转储到一个实现RandomAccess的List中,以便我可以获取索引的任何元素。
Map<String,Object> map = new LinkedHashMap<>();
Set<Map.Entry<String,Object>> st = map.entrySet();
List<Map.Entry<String,Object>> listSort = new ArrayList<>(st);
Collections.sort(listSort,new Comparator<Map.Entry<String,Object>(){
public int compare(Map.Entry<String,Object> entry1,Map.Entry<String,Object> entry2){
return ((Comparable)entry1.getValue).compareTo(entry2.getValue.compareTo);
});
Just iterate the list and you can get the elements sorted
注意: - 我使用匿名内部类实现了一个Comparator,而这个Comparator又使用了Pojo类的Comparable实例