2013-03-07 60 views
5

我如何排序NameValuePair對象這樣的關鍵的NameValuePair排序

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7) 

nameValuePairs.add(new BasicNameValuePair("api_key", "1")); 
nameValuePairs.add(new BasicNameValuePair("merchant", "4")); 
nameValuePairs.add(new BasicNameValuePair("format", "json")); 
nameValuePairs.add(new BasicNameValuePair("method", method)); 
nameValuePairs.add(new BasicNameValuePair("cid", "0")); 
+2

請註明'nameValuePairs' – 2013-03-07 11:41:42

+0

表的類型<的NameValuePair> namevaluepairs中=新的ArrayList <的NameValuePair>(7) – 2013-03-07 11:42:46

回答

13

通行證,其中由鍵排序2個NameValuePair S上的比較。像

Comparator<NameValuePair> comp = new Comparator<NameValuePair>() {  // solution than making method synchronized 
    @Override 
    public int compare(NameValuePair p1, NameValuePair p2) { 
     return p1.getName().compareTo(p2.getName()); 
    } 
} 

// and then 
Collections.sort(pairs, comp); 
+0

非常感謝你! – 2013-03-07 11:45:58

0

東西在Java 8,你可以使用

Collections.sort(pairs, Comparator.comparing(NameValuePair::getName));