1. 程式人生 > >獲取linkedHashMap的最後一個值

獲取linkedHashMap的最後一個值

 

1:通過反射,獲取linkedHashMap的最後一個鍵值對。

 

Map<Integer, Integer> map = new LinkedHashMap<>();            
Field tail = map.getClass().getDeclaredField("tail");
            tail.setAccessible(true);
            Map.Entry<Integer,Integer> entry=(Map.Entry<Integer, Integer>) tail.get(map);
            Integer key = entry.getKey();
            Integer value = entry.getValue();

 

 2: 對Map按照值進行進行排序

 

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> st = map.entrySet().stream();

        st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));

        return result;
    }

 

 3:根據鍵對map進行排序

 

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @program: GradleTestUseSubModule
 **/
public class Main5 {

    public static void salaryfrequeny(int num,int[] salaries) throws NoSuchFieldException, IllegalAccessException {
        Map<Integer, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < num; i++) {
            map.computeIfPresent(salaries[i],(k,v)->{
                return v+1;
            });
            map.putIfAbsent(salaries[i], 1);
        }
        Map<Integer, Integer> sortMap = sortByKey(map);
        System.out.println(sortMap);
    }

    //根據值對map進行排序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> st = map.entrySet().stream();
        st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }
    //根據鍵對map排序
    public static <K extends Comparable,V> Map<K,V> sortByKey(Map<K,V> map) {
        Map<K, V> resultMap = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
        //(a,b)->b.getKey().compareTo(a.getKey())  是一個比較器
        stream.sorted((a,b)->b.getKey().compareTo(a.getKey())).forEach(e->{   //e就是挨個取出map中的Entry,
            System.out.println("key:"+e.getKey()+"  value:"+e.getValue());
            resultMap.put(e.getKey(), e.getValue());
        });
        return resultMap;
    }


    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        int n=5;
        int[] salary = {1000, 2000, 1000, 3000, 2000};
        salaryfrequeny(n,salary);
    }
}

 

 

結果:

key:3000  value:1
key:2000  value:2
key:1000  value:2
{3000=1, 2000=2, 1000=2}