首页 > 解决方案 > 如何通过键集从哈希表中获取所有列表

问题描述

@Test
public void mich() {
    Hashtable<String,List<Path>> mct = new Hashtable<String,List<Path>>();
    List<Path> mm = Arrays.asList(Paths.get("File1"), Paths.get("File2"), Paths.get("File3"));
    List<Path> bb = Arrays.asList(Paths.get("File4"), Paths.get("File5"), Paths.get("File6"));
    List<Path> dd = Arrays.asList(Paths.get("File7"), Paths.get("File8"), Paths.get("File9"));
    mct.put("A",mm);
    mct.put("B",bb);
    mct.put("C",dd);
    List<Path> result = mct.keySet().stream().filter(s -> !s.equalIgnoreCase("C")).peek(System.out::println).map(s -> mct.get(s)).collect(Collectors.toList());
}

我希望我的结果是

File1    
File2    
File3    
File4    
File5    
File6

如何映射我的路径列表?

标签: javajava-8java-stream

解决方案


而不是keySet你必须使用entrySet因为你同时使用键和值来过滤的键和获取路径的值,你还必须像这样使用flatMap

List<Path> result = mct.entrySet().stream()
        .filter(e -> !"C".equalsIgnoreCase(e.getKey()))
        .flatMap(e -> e.values().stream())
        .collect(Collectors.toList());
result.forEach(p -> System.out.println(p.getFileName()));

输出

File1
File2
File3
File4
File5
File6

推荐阅读