Sunday, June 28, 2015

Sorting Key-Value pairs in Java

Saw making your own sorting logic by implementing Comparable or Comparator? If not, click here. Now, how about sorting key-value pairs! Well, we need just a little code modification. See following code sample that sorts key-value pairs, first by key, then values. Look at the compareTo method implementation.

package collections;

import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Sort by key first and then by value
 */
public class KeyValueSortingApp {
    public static void main(String[] args) {
        SortedSet<KeyValuePair> sortedSet = new TreeSet<KeyValuePair>();
        sortedSet.add(new KeyValuePair("icici",400));
        sortedSet.add(new KeyValuePair("icici",200));
        sortedSet.add(new KeyValuePair("icici",50));
        sortedSet.add(new KeyValuePair("sbi",320));
        sortedSet.add(new KeyValuePair("icici",300));
        sortedSet.add(new KeyValuePair("sbi",100));

        for (KeyValuePair pair : sortedSet) {
            System.out.println(pair.key + ":" + pair.value);
        }
    }
}

class KeyValuePair implements Comparable<KeyValuePair> {
    String key;
    int value;
    public KeyValuePair(String key, int value) {
        super();
        this.key = key;
        this.value = value;
    }
    @Override
    public int compareTo(KeyValuePair o) {
        //sort by key, then value
        return key.equalsIgnoreCase(o.key) ? 
            value-o.value : 
            key.compareToIgnoreCase(o.key);
    }
}
Output:
icici:50
icici:200
icici:300
icici:400
sbi:100
sbi:320

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)