You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java8如何从四层嵌套Map中提取最内层的List<Person>集合

Java 8提取四层嵌套Map最内层List的实现方案

场景1:已知四层Map的对应key,安全取值

这种场景推荐用Optional链式调用规避多层嵌套取key可能出现的空指针异常,不需要手写多层if判空逻辑:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public List<Person> getTargetInnerList(
        Map<String, Map<String, Map<String, Map<String, List<Person>>>>> outerMap,
        String firstKey,
        String secondKey,
        String thirdKey,
        String fourthKey
) {
    return Optional.ofNullable(outerMap)
            // 取第一层Map对应值
            .map(firstLayer -> firstLayer.get(firstKey))
            // 取第二层Map对应值
            .map(secondLayer -> secondLayer.get(secondKey))
            // 取第三层Map对应值
            .map(thirdLayer -> thirdLayer.get(thirdKey))
            // 取第四层Map对应值即目标List
            .map(fourthLayer -> fourthLayer.get(fourthKey))
            // 任意一层为空时返回空集合,避免空指针
            .orElseGet(ArrayList::new);
}

如果完全确定每层key都存在不会为空,可以直接简写,但不推荐,中间任意一层为null都会抛出NullPointerException:

List<Person> personList = outerMap.get(firstKey).get(secondKey).get(thirdKey).get(fourthKey);

场景2:不需要指定key,提取所有最内层的List

如果要把嵌套结构里所有最内层的List<Person>全部拉平处理,用Stream的flatMap逐层展开即可:

合并所有Person为一个大集合

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public List<Person> getAllPersons(Map<String, Map<String, Map<String, Map<String, List<Person>>>>> outerMap) {
    return outerMap.values().stream()
            .flatMap(secondLayer -> secondLayer.values().stream())
            .flatMap(thirdLayer -> thirdLayer.values().stream())
            .flatMap(fourthLayer -> fourthLayer.values().stream())
            .flatMap(List::stream)
            .collect(Collectors.toList());
}

保留每个独立的List不合并元素

去掉最后一层flatMap(List::stream)即可,返回值为所有内层List的集合:

public List<List<Person>> getAllInnerLists(Map<String, Map<String, Map<String, Map<String, List<Person>>>>> outerMap) {
    return outerMap.values().stream()
            .flatMap(secondLayer -> secondLayer.values().stream())
            .flatMap(thirdLayer -> thirdLayer.values().stream())
            .flatMap(fourthLayer -> fourthLayer.values().stream())
            .collect(Collectors.toList());
}

内容的提问来源于stack exchange,提问作者Rayan Machin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 18:21:01