获取linkedHashMap的最后一个值

 

1:通过反射,获取linkedHashMap的最后一个键值对。

 

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

 

 2: 对Map按照值进行进行排序

 

public static > Map sortByValue(Map map) {
        Map result = new LinkedHashMap<>();
        Stream> 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 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 sortMap = sortByKey(map);
        System.out.println(sortMap);
    }

    //根据值对map进行排序
    public static > Map sortByValue(Map map) {
        Map result = new LinkedHashMap<>();
        Stream> st = map.entrySet().stream();
        st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }
    //根据键对map排序
    public static  Map sortByKey(Map map) {
        Map resultMap = new LinkedHashMap<>();
        Stream> 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}

你可能感兴趣的:(java)