当前位置:天才代写 > tutorial > JAVA 教程 > java map凭据value值来较量巨细而且返回最终功效

java map凭据value值来较量巨细而且返回最终功效

2017-11-02 08:00 星期四 所属: JAVA 教程 浏览:525

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

查察本栏目

 

    关键字:

天才代写-代写联系方式