编程题——HashMap排序

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

  • 通过entrySet()拿到键值对  Set<Entry<Integer,User>> entrySet=map.entrySet();
  • 将set集合转化为list集合     List<Entry<Integer,User>> list= new ArrayList<Entry<Integer,User>> (entrySet);
  •  使用 Collections 集合工具类对List 进行 排序,排序规则使用匿名内部类来实现
     Collections.sort(intList,new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                // 返回值为int类型,大于0表示正序,小于0表示逆序
                return o2-o1;
            }
        });
  • 创建新的有序hashmap子类的集合  LinkedHashMap<Integer,User> linkedHashMap=new LinkedHashMap<Integer,User>();
  • 将List中的数据存储在 LinkedHashMap中
  • 返回数据

代码实现

package JBTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

class User{
	private String name;
	private int age;
	
	public User(){}
	public User(String name,int age){
		this.name=name;
		this.age=age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}
	
	
}
 
public class HashMapTest {
	//
	public static void main(String[] args) {
		HashMap<Integer,User> users=new HashMap<>();
		
		users.put(1, new User("张三",25));
		users.put(3, new User("李四",22));
		users.put(2, new User("王五",28));
		
		System.out.println(users);
		
		HashMap<Integer,User> sortHashMap=sortHashMap(users);
		System.err.println(sortHashMap);
		
	}
	// 定义一个进行排序的方法
	// 要求实现 对 HashMap 集合中 value值 即User 对象的 age 属性,进行 排序
	
	public static HashMap<Integer,User> sortHashMap(HashMap<Integer,User> map){
		// 拿到 map集合键值对
		Set<Entry<Integer,User>> entrySet=map.entrySet();
	    // 将 set 集合 转化为 List 集合
		List<Entry<Integer,User>> list= new ArrayList<Entry<Integer,User>> (entrySet);
		// 使用 Collections 集合 工具类 对List 进行 排序,排序规则使用 匿名内部类来实现
		Collections.sort(list,new Comparator<Entry<Integer,User>>(){
			
			// 安照要求 根据 User 的age 的倒序进行排序
			
			public int compare(Entry<Integer,User> o1,Entry<Integer,User> o2){
				return o2.getValue().getAge()-o1.getValue().getAge();
			}
			
		});
		
		// 创建 新的 有序的 hahMap 子类的集合
		LinkedHashMap<Integer,User> linkedHashMap=new LinkedHashMap<Integer,User>();
		
		// 将 List 中的数据 存储 在 LinkedHashMap中
		for(Entry<Integer,User> entry:list){
			linkedHashMap.put(entry.getKey(),entry.getValue());
		}
		
		return linkedHashMap;
		
	}
	
 
}

猜你喜欢

转载自blog.csdn.net/hd12370/article/details/81367066