java - Trier une carte géographiqueKey, Valeur vaccinée par des valeurs

Mots clés : javasortingdictionarycollectionsjava

meilleur 5 Réponses java - Trier une carte géographiqueKey, Valeur vaccinée par des valeurs

vote vote

99

public class MapUtil {     public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {         List<Entry<K, V>> list = new ArrayList<>(map.entrySet());         list.sort(Entry.comparingByValue());          Map<K, V> result = new LinkedHashMap<>();         for (Entry<K, V> entry : list) {             result.put(entry.getKey(), entry.getValue());         }          return result;     } } 
vote vote

87

public class Testing {     public static void main(String[] args) {         HashMap<String, Double> map = new HashMap<String, Double>();         ValueComparator bvc = new ValueComparator(map);         TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);          map.put("A", 99.5);         map.put("B", 67.4);         map.put("C", 67.4);         map.put("D", 67.3);          System.out.println("unsorted map: " + map);         sorted_map.putAll(map);         System.out.println("results: " + sorted_map);     } }  class ValueComparator implements Comparator<String> {     Map<String, Double> base;      public ValueComparator(Map<String, Double> base) {         this.base = base;     }      // Note: this comparator imposes orderings that are inconsistent with     // equals.     public int compare(String a, String b) {         if (base.get(a) >= base.get(b)) {             return -1;         } else {             return 1;         } // returning 0 would merge keys     } } 
unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4} results: {D=67.3, B=67.4, C=67.4, A=99.5} 
vote vote

74

Stream<Map.Entry<K,V>> sorted =     map.entrySet().stream()        .sorted(Map.Entry.comparingByValue()); 
Stream<Map.Entry<K,V>> sorted =     map.entrySet().stream()        .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())); 
Stream<Map.Entry<K,V>> sorted =     map.entrySet().stream()        .sorted(Map.Entry.comparingByValue(comparator)); 
Map<K,V> topTen =     map.entrySet().stream()        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))        .limit(10)        .collect(Collectors.toMap(           Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); 
map.entrySet().stream()    .sorted(Map.Entry.comparingByValue())    .forEach(System.out::println); 
vote vote

63

valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)) 
valueComparator = Ordering.from(comparator).onResultOf(Functions.forMap(map))  
valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)).compound(Ordering.natural()) 
map = ImmutableSortedMap.copyOf(myOriginalMap, valueComparator); 
import static org.junit.Assert.assertEquals;  import java.util.HashMap; import java.util.Map; import java.util.TreeMap;  import com.google.common.base.Functions; import com.google.common.collect.Ordering;  class ValueComparableMap<K extends Comparable<K>,V> extends TreeMap<K,V> {     //A map for doing lookups on the keys for comparison so we don't get infinite loops     private final Map<K, V> valueMap;      ValueComparableMap(final Ordering<? super V> partialValueOrdering) {         this(partialValueOrdering, new HashMap<K,V>());     }      private ValueComparableMap(Ordering<? super V> partialValueOrdering,             HashMap<K, V> valueMap) {         super(partialValueOrdering //Apply the value ordering                 .onResultOf(Functions.forMap(valueMap)) //On the result of getting the value for the key from the map                 .compound(Ordering.natural())); //as well as ensuring that the keys don't get clobbered         this.valueMap = valueMap;     }      public V put(K k, V v) {         if (valueMap.containsKey(k)){             //remove the key in the sorted set before adding the key again             remove(k);         }         valueMap.put(k,v); //To get "real" unsorted values for the comparator         return super.put(k, v); //Put it in value order     }      public static void main(String[] args){         TreeMap<String, Integer> map = new ValueComparableMap<String, Integer>(Ordering.natural());         map.put("a", 5);         map.put("b", 1);         map.put("c", 3);         assertEquals("b",map.firstKey());         assertEquals("a",map.lastKey());         map.put("d",0);         assertEquals("d",map.firstKey());         //ensure it's still a map (by overwriting a key, but with a new value)          map.put("d", 2);         assertEquals("b", map.firstKey());         //Ensure multiple values do not clobber keys         map.put("e", 2);         assertEquals(5, map.size());         assertEquals(2, (int) map.get("e"));         assertEquals(2, (int) map.get("d"));     }  } 
 new ValueComparableMap(Ordering.natural());  //or  new ValueComparableMap(Ordering.from(comparator)); 
vote vote

58

private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {     List<Entry<K, V>> list = new LinkedList<>(map.entrySet());     Collections.sort(list, new Comparator<Object>() {         @SuppressWarnings("unchecked")         public int compare(Object o1, Object o2) {             return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());         }     });      Map<K, V> result = new LinkedHashMap<>();     for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {         Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();         result.put(entry.getKey(), entry.getValue());     }      return result; } 

Questions similaires