NameValuePair排序

时间:2013-03-07 11:38:29

标签: java apache

如何通过键

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 个答案:

答案 0 :(得分:13)

传入比较器,按键对两个NameValuePair进行排序。像

这样的东西
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);

答案 1 :(得分:2)

在Java 8中,您可以使用

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