使用Java8流过滤Map的密钥后映射到List

use*_*485 5 java list hashmap java-8 collectors

我有一个Map<String, List<String>>.我希望在对地图的键进行过滤后将此地图转换为List.

例:

Map<String, List<String>> words = new HashMap<>();
List<String> aList = new ArrayList<>();
aList.add("Apple");
aList.add("Abacus");

List<String> bList = new ArrayList<>();
bList.add("Bus");
bList.add("Blue");
words.put("A", aList);
words.put("B", bList);
Run Code Online (Sandbox Code Playgroud)

给出一个关键,比如"B"

Expected Output: ["Bus", "Blue"]
Run Code Online (Sandbox Code Playgroud)

这就是我想要的:

 List<String> wordsForGivenAlphabet = words.entrySet().stream()
    .filter(x-> x.getKey().equalsIgnoreCase(inputAlphabet))
    .map(x->x.getValue())
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

我收到了一个错误.有人可以在Java8中为我提供一种方法吗?

Ber*_*eri 12

你的sniplet会产生一个List<List<String>>没有List<String>.

您缺少flatMap,它会将列表流转换为单个流,因此基本上会展平您的流:

List<String> wordsForGivenAlphabet = words.entrySet().stream()
    .filter(x-> x.getKey().equalsIgnoreCase(inputAlphabet))
    .map(Map.Entry::getValue)
    .flatMap(List::stream) 
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

distinct()如果您不希望重复值,也可以添加.