View difference between Paste ID: bWhbHQmT and
SHOW: | | - or go back to the newest paste.
1-
1+
package util;
2
3
import java.util.Collections;
4
import java.util.Comparator;
5
import java.util.HashMap;
6
import java.util.Iterator;
7
import java.util.LinkedList;
8
import java.util.LinkedHashMap;
9
import java.util.List;
10
import java.util.Map;
11
12
public class SortableValueMap<K, V> extends LinkedHashMap<K, V> {
13
  public SortableValueMap() { }
14
15
  public SortableValueMap( Map<K, V> map ) {
16
    super( map );
17
  }
18
19
  public void sortByValue() {
20
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( entrySet() );
21
22
    Collections.sort( list, new Comparator<Map.Entry>() {
23
      public int compare( Map.Entry entry1, Map.Entry entry2 ) {
24
        return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
25
      }
26
    });
27
28
    clear();
29
30
    for( Map.Entry<K, V> entry : list ) {
31
      put( entry.getKey(), entry.getValue() );
32
    }
33
  }
34
35
  private static void print( String text, Map<String, Double> map ) {
36
    System.out.println( text );
37
38
    for( String key : map.keySet() ) {
39
      System.out.println( "key/value: " + key + "/" + map.get( key ) );
40
    }
41
  }
42
43
  public static void main(String[] args) {
44
    SortableValueMap<String, Double> map =
45
      new SortableValueMap<String, Double>();
46
47
    map.put( "A", 67.5 );
48
    map.put( "B", 99.5 );
49
    map.put( "C", 82.4 );
50
    map.put( "D", 42.0 );
51
52
    print( "Unsorted map", map );
53
    map.sortByValue();
54
    print( "Sorted map", map );
55
  }
56
}