java map按照value值來比較大小並且返回最終結果

來源:互聯網
上載者:User
package com.zuidaima.util;        import java.util.Comparator;  import java.util.HashMap;  import java.util.Map;  import java.util.TreeMap;        public class ValueComparator implements Comparator<Long> {            Map<Long, Double> base;            public ValueComparator(Map<Long, Double> base) {          this.base = base;      }            public int compare(Long a, Long b) {          if (base.get(a).doubleValue() >= base.get(b).doubleValue()) {              return -1;          } else {              return 1;          }      }            public static <K, V extends Comparable<V>> Map<K, V> sortByValues(              final Map<K, V> map) {          Comparator<K> valueComparator = new Comparator<K>() {              public int compare(K k1, K k2) {                  int compare = map.get(k2).compareTo(map.get(k1));                  if (compare == 0)                      return 1;                  else                    return compare;              }          };          Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);          sortedByValues.putAll(map);          return sortedByValues;      }            public static void main(String[] args) {          HashMap<Long, Double> map = new HashMap<Long, Double>();          map.put(1l, 99.5);          map.put(2l, 67.2);          map.put(3l, 67.5);          map.put(4l, 67.6);                ValueComparator bvc = new ValueComparator(map);          TreeMap<Long, Double> sorted_map = new TreeMap<Long, Double>(bvc);                System.out.println("unsorted map: " + map);                sorted_map.putAll(map);                System.out.println("results: " + sorted_map);                Map<Long, Double> sorted_map2 = sortByValues(map);                        System.out.println("results2: " + sorted_map2);      }  }

輸出結果:

unsorted map: {1=99.5, 2=67.2, 3=67.5, 4=67.6}

results: {1=99.5, 4=67.6, 3=67.5, 2=67.2}

results2: {1=99.5, 4=67.6, 3=67.5, 2=67.2}

通過key比較大小的原理類似,大家改寫下就好了。enjoy it。

原文:http://www.zuidaima.com/share/1830834176347136.htm

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.