前言:创建一个HashMap对象,用于存储员工的信息(员工的信息有员工工号,姓名和工资),然后根据工资从高到低的顺序排序。
1、Employee 实体类
package cn.nnxy;
/**
* 员工类
* @author clm
*@date 2021年3月30日 下午7:02:07
*/
public class Employee {
private Integer id;
private String name;
private Integer salary;
public Employee() {
}
public Employee(Integer id,String name,Integer salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return "工号:" + id +"---"+ "姓名:" + name + "---"+"工资:" + salary;
}
}
2、HashMapTest 测试类
package cn.nnxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* HashMap
*
* @author clm
* @date 2021年3月30日 下午6:48:05
*/
public class HashMapTest {
public static void main(String[] args) {
/*
* 将数据添加到hashmap
*/
HashMap<Integer, Employee> staff = new HashMap<>();
staff.put(1, new Employee(2001, "小花", 6000));
staff.put(2, new Employee(2003, "李四", 5500));
staff.put(3, new Employee(2002, "小玉", 4000));
staff.put(4, new Employee(2004, "张三", 5000));
System.out.println("------------排序前-----------");
Iterator<Entry<Integer, Employee>> it = staff.entrySet().iterator();
/*
* 遍历员工信息
*/
while (it.hasNext()) {
Entry<Integer, Employee> entry = it.next();
System.out.println(entry.getKey() + "---" + entry.getValue());
}
System.out.println("------------排序后(降序)-----------");
HashMap<Integer, Employee> sortHashMap = sortHashMap(staff);
Iterator<Entry<Integer, Employee>> sort = sortHashMap.entrySet().iterator();
while (sort.hasNext()) {
Entry<Integer, Employee> entry = sort.next();
System.out.println(entry.getKey() + "---" + entry.getValue());
}
}
public static HashMap<Integer, Employee> sortHashMap(HashMap<Integer, Employee> map) {
/*
* 拿到 map 的键值对集合
*/
Set<Map.Entry<Integer, Employee>> entrySet = map.entrySet();
/*
* 将 set 集合转为 List 集合
*/
List<Map.Entry<Integer, Employee>> list = new ArrayList<Map.Entry<Integer, Employee>>(entrySet);
/*
* 使用 Collections 集合工具类对 list 进行排序
*/
Collections.sort(list, new Comparator<Map.Entry<Integer, Employee>>() {
public int compare(Map.Entry<Integer, Employee> o1, Map.Entry<Integer, Employee> o2) {
/*
* 根据 Employee 的 salary 进行降序排序,如果是升序则o1-o2
*/
return (o2.getValue().getSalary() - o1.getValue().getSalary());
}
});
/*
* 创建一个新的有序的 HashMap
*/
LinkedHashMap<Integer, Employee> linkedHashMap = new LinkedHashMap<Integer, Employee>();
/*
* 将 List 中的数据存储在 LinkedHashMap 中
*/
for (Map.Entry<Integer, Employee> entry : list) {
linkedHashMap.put(entry.getKey(), entry.getValue());
}
// 返回结果
return linkedHashMap;
}
}
3、效果图