Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameValuePair sort

Tags:

java

apache

How can I sort NameValuePair objects like this by key

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"));
like image 927
Artem Cherkasov Avatar asked Mar 07 '13 11:03

Artem Cherkasov


2 Answers

Pass in the Comparator which sorts two NameValuePairs by key. Something like

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);
like image 91
mindas Avatar answered Nov 10 '22 19:11

mindas


In Java 8 you can use

Collections.sort(pairs, Comparator.comparing(NameValuePair::getName));
like image 22
stiebrs Avatar answered Nov 10 '22 19:11

stiebrs