5

如何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"));
4

2 回答 2

13

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);
于 2013-03-07T11:44:59.423 回答
2

在 Java 8 中,您可以使用

Collections.sort(pairs, Comparator.comparing(NameValuePair::getName));
于 2018-02-02T07:48:58.253 回答