gpt4 book ai didi

java - 从 Hashmap 的所有值中获取所有嵌套项

转载 作者:行者123 更新时间:2023-12-02 10:51:59 24 4
gpt4 key购买 nike

我使用了 HashMap,键为字符串,值为 ArrayList:

HashMap<String, ArrayList<Student>> students;

如何取回所有 Student 对象,即所有 ArrayList 对象的所有元素?

最佳答案

如果您想要所有Student,您可以通过Mapvalues()进行Stream并使用 flatMap 展平 Stream:

List<Students> studentList = students.values() // Collection<ArrayList<Students>>
.stream() // Stream<ArrayList<Students>>
.flatMap(List::stream) // Stream<Students>
.collect(Collectors.toList());

如果您无法使用 Java 8,则必须迭代 Mapvalues() 并将它们全部添加到 列表:

List<Students> studentList = new ArrayList<>();
for (ArrayList<Students> list : students.values())
studentList.addAll(list);

关于java - 从 Hashmap 的所有值中获取所有嵌套项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48048197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com