要根据年龄排序输出 map,可以使用 Java 8 中的 Stream API 来实现。具体步骤如下:

  1. 创建一个 HashMap 对象,并向其中添加 emp 对象。例如:
Map<String, Emp> map = new HashMap<>();
map.put('emp1', new Emp('Alice', 25));
map.put('emp2', new Emp('Bob', 30));
map.put('emp3', new Emp('Charlie', 20));
  1. 使用 Stream API 对 map 的 value 进行排序。可以使用Stream#sorted方法,并通过Comparator.comparing方法指定排序依据,例如按照年龄升序排序:
List<Map.Entry<String, Emp>> sortedList = map.entrySet().stream()
    .sorted(Comparator.comparing(entry -> entry.getValue().getAge()))
    .collect(Collectors.toList());
  1. 遍历排序后的列表,并输出每个键值对的信息:
for (Map.Entry<String, Emp> entry : sortedList) {
    System.out.println(entry.getKey() + ': ' + entry.getValue().getName() + ', ' + entry.getValue().getAge());
}

完整的示例代码如下:

import java.util.*;
import java.util.stream.Collectors;

class Emp {
    private String name;
    private int age;

    public Emp(String name, int age) {
        this.name = name;
        this.age = age;
    } 

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Map<String, Emp> map = new HashMap<>();
        map.put('emp1', new Emp('Alice', 25));
        map.put('emp2', new Emp('Bob', 30));
        map.put('emp3', new Emp('Charlie', 20));

        List<Map.Entry<String, Emp>> sortedList = map.entrySet().stream()
                .sorted(Comparator.comparing(entry -> entry.getValue().getAge()))
                .collect(Collectors.toList());

        for (Map.Entry<String, Emp> entry : sortedList) {
            System.out.println(entry.getKey() + ': ' + entry.getValue().getName() + ', ' + entry.getValue().getAge());
        }
    }
}

运行以上代码,输出结果为:

emp3: Charlie, 20
emp1: Alice, 25
emp2: Bob, 30
Java HashMap 排序:使用 Stream API 按年龄排序

原文地址: https://www.cveoy.top/t/topic/o0OM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录