java - Sort LinkedHashMap using Comparable based on object attribute -


i want sort linkedhashmap based on object attribute , using comparable. here code:

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

so u need first dump entryset list , sort it.you can't sort set unless using treeset.i prefer dump list implements randomaccess can fetch element index.

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);  });    iterate list , can elements sorted  

note:- have implemented comparator using anonymous inner class , comparator in turn uses comparable instance of pojo class


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -