问题与Java 8 API流相关。需要筛选不存在的键。

huangapple go评论82阅读模式
英文:

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&lt;String&gt; myList = Arrays.asList(&quot;key1&quot;, &quot;key2&quot;, &quot;key3&quot;);

and a map:

Map&lt;String, String&gt; myMap = Map.of(&quot;key1&quot;,&quot;VALUE1&quot;, &quot;key2&quot;, &quot;VALUE2&quot;);

When I do the following:

myList.stream().map(i-&gt;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 = &quot;Map does not contain such key&quot;;
myList.stream().map(i -&gt; 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&lt;String&gt; myList = Arrays.asList(&quot;key1&quot;, &quot;key2&quot;, &quot;key3&quot;, &quot;key4&quot;, &quot;key5&quot;);
Map&lt;String, String&gt; myMap = Map.of(&quot;key1&quot;,&quot;VALUE1&quot;, &quot;key2&quot;, &quot;VALUE2&quot;);
List&lt;String&gt; results = myList.stream()
             .map(i-&gt; myMap.getOrDefault(i, &quot;Doesn&#39;t exist for &#39;&quot; + i + &quot;&#39;&quot;))
             .collect(Collectors.toList());

results.forEach(System.out::println);

Prints

VALUE1
VALUE2
Doesn&#39;t exist for &#39;key3&#39;
Doesn&#39;t exist for &#39;key4&#39;
Doesn&#39;t exist for &#39;key5&#39;

	

</details>



huangapple
  • 本文由 发表于 2020年10月19日 19:37:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64426543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定