2012-03-23 18 views
0

Supose我有名字Mink,Mark,Aashis。如何比較它們並按字母順序排列它們。 Collections.sort()不爲我工作。在這裏,我應該有結果Aashis,Mark and Mark如何比較HashMap的字符串並排列它們?

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 
HashMap<String, String> map = new HashMap<String, String>(); 
map.put("name", XMLfunctions.getValue(e, "name")); 
       mylist.add(map); 

       Collections.sort(mylist, new Comparator<HashMap<String,String>>(){      

        public int compare(HashMap<String, String> lhs, 
          HashMap<String, String> rhs) { 
          //how do i compare string name 
         return 0; 

        } 
       }); 
+1

包含HashMap是無序的。 – SLaks 2012-03-23 06:07:57

+0

你已經展示了一張地圖列表*,但你的例子只是談論3個地名。什麼是映射? – 2012-03-23 06:10:32

+0

名稱是我已經解析並在列表視圖中列出的XML標記。我想根據名稱,編號等來安排該列表。現在如何比較它們? – captaindroid 2012-03-23 06:14:21

回答

2
Collections.sort(list, new Comparator(){ 

public int compare(HashMap<String, String> o1, HashMap<String, String> o2) { 
     return (o1.get("name")).compareToIgnoreCase(o2.get("name")); 
    } 

這裏的「名」是你在插入使用put方法HashMap中時提供的密鑰。

EXTRA

如果你想分析的double值,那麼你可以使用Double.parse()方法。

return Double.compare(o1.get(value1),o1.get(value2));

注 - 這種方法的好處是你可以通過任何屬性或甚至屬性的組合對任何對象進行排序。例如,如果您的Person類型的對象具有屬性收入和dataOfBirth,則可以定義Comparator的不同實現並根據需要對對象進行排序。

希望這會幫助你。

+0

suprrr ...這個作品夥計。 Thanx! – captaindroid 2012-03-23 06:55:08

+0

So Enjoy coding ....... – Prem 2012-03-23 06:56:06

+0

這裏是否有任何錯誤'String s1 = o1.get(「score」); \t \t \t \t \t \t \t \t字符串s2 = o2.get( 「分數」); \t \t \t \t \t \t \t \t雙s1Value = Double.parseDouble(S1); \t \t \t \t \t \t \t \t雙s2Value = Double.parseDouble(S2); \t \t \t \t \t \t \t \t返回Double.compare(s1Value,s2Value);' 它爲字符串,但沒有工作的工作爲雙正如我上面編寫代碼。 – captaindroid 2012-03-23 07:13:29

2

試試這個代碼

插入值

public ArrayList<HashMap<String, String>> list; 
list = new ArrayList<HashMap<String, String>>(); 

for (int i = 0; i < 5; i++) { 

      HashMap<String, String> info = new HashMap<String, String>(); 

      info.put("title", "gdfgdfgdfgdfggdfgfdgdgdgdffghfghfgh"); 
      info.put("time", "44:55"); 
      info.put("view", "54,353"); 

      list.add(info); 

     } 

獲取和比較

String title1 = ketan; 



for (int i = 0; i < list.size(); i++) { 

HashMap<String, String> map = new HashMap<String, String>(); 
     map = list.get(i); 

     if(map.get("title")==title1); 
       { 
        ........ 
        ...... 
       }  
    } 
相關問題