我有一个Map<String, List<String>>
.我想在过滤地图键后将此地图转换为列表。
例:
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);
给定一个键,比如"B">
Expected Output: ["Bus", "Blue"]
这就是我正在尝试的:
List<String> wordsForGivenAlphabet = words.entrySet().stream()
.filter(x-> x.getKey().equalsIgnoreCase(inputAlphabet))
.map(x->x.getValue())
.collect(Collectors.toList());
我收到错误。有人可以为我提供一种在 Java8 中做到这一点的方法吗?
你的剪影会产生一个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());
如果不希望值重复,也可以添加distinct()
。
Federico 在他的评论中是对的,如果您只想获取某个键的值(在List
内(,为什么不简单地做一个get
(假设你所有的键都是大写字母(?
List<String> values = words.get(inputAlphabet.toUpperCase());
另一方面,如果这只是为了了解流操作的工作原理,那么还有另一种方法可以做到这一点(通过java-9Collectors.flatMapping
List<String> words2 = words.entrySet().stream()
.collect(Collectors.filtering(x -> x.getKey().equalsIgnoreCase(inputAlphabet),
Collectors.flatMapping(x -> x.getValue().stream(),
Collectors.toList())));
正如之前在collect
之后所说,您将获得只有一个或零值的List<List<String>>
。您可以使用findFirst
而不是collect
它会返回您Optional<List<String>>
。