HashMap实现按照key和value进行排序

HashMap添加元素是无序的,下面是按照key和User中的age进行排序

已知一个 HashMap<Integer,User> 集合,User 有 name(String)和 age(int)属性。请写一个方法实现对HashMap的排序功能,该方法接收HashMap<Integer,User>为形参,返回类型为 HashMap<Integer,User>,要求对 HashMap 中的 User 的 age 倒序进行排序。排序时 key=value 键值对不得拆散。 
 

package com.hf.mypractice.Javabase;

import com.hf.mypractice.model.User;
import org.junit.Before;
import org.junit.Test;

import java.util.*;

/**
 * @Description: hashmap根据 key,value进行sort
 * @Date: 2019/1/18
 * @Auther: 
 */
public class HashMapSort {

    private static Map<Integer, User> map = null;

    @Before
    public void init(){
      map = new HashMap<Integer, User>() {{
            for (int i = 0; i < 5; i++) {
                User user = new User("yu" + i, 10 + i);
                put(i, user);
            }
        }};
    }

    /**
     * 通过key排序,还是输出hashMap
     */
    @Test
    public void sortByKey(){
       //将map转换为list,进行排序,原因是使用Collections工具类中的排序方法,compare
        List<Map.Entry<Integer, User>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list,(o1,o2) -> {
            return o2.getKey() - o1.getKey();
        });

        map.clear();
       map =  new LinkedHashMap<Integer,User>(){{
            list.forEach(mm -> {
                put(mm.getKey(),mm.getValue());
            });
        }};

       map.forEach((key,value) -> {
           System.out.println("排序后的key为:" + key + "....对应的user对象的name为:" + value.getName());
       });
    }

    /**
     * 按照user对象中的属性,age降序进行排序,还是返回HashMap集合
     */
    @Test
    public void sortByValue(){
        //将map转换为list,进行排序,原因是使用Collections工具类中的排序方法,compare
     List<Map.Entry<Integer, User>> list = new ArrayList<>(map.entrySet());

     //排序
        Collections.sort(list,(o1,o2) -> {
            return o2.getValue().getAge() - o1.getValue().getAge();
        });

        map.clear();
        //使用LinkedHashMap来接收,因为LinkedHashMap有序,并且其父类是HashMap
       map =  new LinkedHashMap<Integer,User>(){{
            list.forEach(mm -> {
                put(mm.getKey(),mm.getValue());
            });
        }};

       map.forEach((key,value) -> {
           System.out.println("排序后的user对象中的age是:" + value.getAge() + "....name:" + value.getName());
       });

    }
}

猜你喜欢

转载自blog.csdn.net/qq_42151769/article/details/86540675