Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package util;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- public class SortableValueMap<K, V> extends LinkedHashMap<K, V> {
- public SortableValueMap() { }
- public SortableValueMap( Map<K, V> map ) {
- super( map );
- }
- public void sortByValue() {
- List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( entrySet() );
- Collections.sort( list, new Comparator<Map.Entry>() {
- public int compare( Map.Entry entry1, Map.Entry entry2 ) {
- return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
- }
- });
- clear();
- for( Map.Entry<K, V> entry : list ) {
- put( entry.getKey(), entry.getValue() );
- }
- }
- private static void print( String text, Map<String, Double> map ) {
- System.out.println( text );
- for( String key : map.keySet() ) {
- System.out.println( "key/value: " + key + "/" + map.get( key ) );
- }
- }
- public static void main(String[] args) {
- SortableValueMap<String, Double> map =
- new SortableValueMap<String, Double>();
- map.put( "A", 67.5 );
- map.put( "B", 99.5 );
- map.put( "C", 82.4 );
- map.put( "D", 42.0 );
- print( "Unsorted map", map );
- map.sortByValue();
- print( "Sorted map", map );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement