如何通过键
对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"));
答案 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));