NameValuePair sort

How can I sort NameValuePairobjects like this with a 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"));
+5
source share
2 answers

In Java 8 you can use

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

Go to the comparator, which sorts the two NameValuePairby key. Sort of

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);
+13
source

All Articles