要根据生成的 Map 按 Key 的顺序将 Value 生成 List,可以使用 Java 8 的 Stream API 和 Collectors.toList() 方法来实现。以下是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put('A', 1);
        map.put('B', 2);
        map.put('C', 3);

        List<Integer> list = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

        System.out.println(list); // 输出 [1, 2, 3]
    }
}

在以上示例中,我们首先创建了一个 Map 对象,并将键值对添加到其中。然后,我们使用 entrySet() 方法获取 Map 的键值对集合,并通过 stream() 方法将其转换为流。接下来,我们使用 sorted() 方法按照 Key 的顺序对流进行排序。最后,我们使用 map() 方法将流中的每个键值对转换为其对应的 Value,并使用 collect() 方法将结果收集到一个 List 中。

请注意,这里使用的是 Entry.comparingByKey() 方法来对 Key 进行排序。如果要根据 Value 进行排序,则可以使用 Entry.comparingByValue() 方法。

Java List Stream GroupBy: 将 Map 按 Key 顺序排序并提取 Value 为 List

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

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