Pat*_*tty 6 java lambda java-8 java-stream collectors
Map<Integer, String> map = new HashMap<>();
map.put(1, "f");
map.put(2, "i");
map.put(3, "a");
map.put(4, "c");....etc
Run Code Online (Sandbox Code Playgroud)
现在我有一个列表:
List<Integer> picks = {1,3}
Run Code Online (Sandbox Code Playgroud)
我想取回一个字符串列表,即映射中与“ pick”列表中找到的键值匹配的值。因此,我希望取回{“ f”,“ a”}作为结果。有没有一种方法可以使用Java流api优雅地做到这一点?
当有一个值时,我就是这样:
map.entrySet().stream()
.filter(entry -> "a".equals(entry.getValue()))
.map(entry -> entry.getValue())
.collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)
但是,当要过滤的键/小贴士列表变得越来越困难时。
您可以使用以下方法实现此目的:
List<String> values = map.entrySet()
.stream()
.filter(entry -> picks.contains(entry.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
values.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
输出:
f
a
Run Code Online (Sandbox Code Playgroud)
但是,它可能不是List::containsO(N)那样有效。考虑使用Set(例如HashSet),而不是List对picks作为HashSet::contains是O(1)。
您可以List.contains()在中使用Stream#filter以仅接受列表中存在的那些值:
List<String> result = map.entrySet()
.stream()
.filter(ent -> picks.contains(ent.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
You don't need to traverse the entire map just to collect picked values. Rather iterate over the required keys and grab the relevant values from the map. If the map is far more larger compared to the values you need to pick which is usually the case, then this approach should outperform the other. Moreover this solution is much more compact and has less visual clutter to me. Here's how it looks.
List<String> pickedValues = picks.stream().map(map::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
235 次 |
| 最近记录: |