英文:
Issue with java 8 api stream. Need to filter non existent keys
问题
我有一个列表:
List<String> myList = Arrays.asList("key1", "key2", "key3");
和一个映射:
Map<String, String> myMap = Map.of("key1", "VALUE1", "key2", "VALUE2");
当我执行以下操作:
myList.stream().map(i -> myMap.get(i)).collect(Collectors.toList());
我得到以下输出:
[VALUE1, VALUE2, null]
如何调整我的逻辑,以便在输出中不是 "null",而是类似于字符串 "Map does not contain such key"?
英文:
I have a list:
List<String> myList = Arrays.asList("key1", "key2", "key3");
and a map:
Map<String, String> myMap = Map.of("key1","VALUE1", "key2", "VALUE2");
When I do the following:
myList.stream().map(i->myMap.get(i)).collect(Collectors.toList());
I have the following output:
[VALUE1, VALUE2, null]
How can I do my logic so that I have something like a String "Map does not contain such key" instead of "null" in my output?
答案1
得分: 4
你可以使用 Map
类的 .getOrDefault(key, defaultValue)
方法。这里是一个例子:
String defaultText = "Map中不包含该键";
myList.stream().map(i -> myMap.getOrDefault(i, defaultText)).collect(Collectors.toList());
英文:
You can use the .getOrDefault(key, defaultValue)
method of the Map
class. Here's an example:
String defaultText = "Map does not contain such key";
myList.stream().map(i -> myMap.getOrDefault(i, defaultText)).collect(Collectors.toList());
答案2
得分: 0
我会对UtkuÖzdemir'的出色答案进行以下更改。
记录键和文本,这样,您就可以确切地知道缺少了哪个键。
List<String> myList = Arrays.asList("key1", "key2", "key3", "key4", "key5");
Map<String, String> myMap = Map.of("key1", "VALUE1", "key2", "VALUE2");
List<String> results = myList.stream()
.map(i-> myMap.getOrDefault(i, "不存在的键: '" + i + "'"))
.collect(Collectors.toList());
results.forEach(System.out::println);
输出结果:
VALUE1
VALUE2
不存在的键: 'key3'
不存在的键: 'key4'
不存在的键: 'key5'
英文:
I would make the following change to UtkuÖzdemir's excellent answer.
Record the key along with the text, that way, you know exactly which key was missing.
List<String> myList = Arrays.asList("key1", "key2", "key3", "key4", "key5");
Map<String, String> myMap = Map.of("key1","VALUE1", "key2", "VALUE2");
List<String> results = myList.stream()
.map(i-> myMap.getOrDefault(i, "Doesn't exist for '" + i + "'"))
.collect(Collectors.toList());
results.forEach(System.out::println);
Prints
VALUE1
VALUE2
Doesn't exist for 'key3'
Doesn't exist for 'key4'
Doesn't exist for 'key5'
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论