使用基于Optional< Map>的内容的流 [英] using a stream based on the content of Optional<Map>

查看:237
本文介绍了使用基于Optional< Map>的内容的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从不受我控制的服务中获取了一张地图,该服务可能为空,并且想要处理它,比如说,过滤,映射和缩减为我需要的单个元素。



问题:从可选到流是否有链接?



我尝试过(除其他事项外):

  return Optional.ofNullable(getMap())
.map(Map :: entrySet)//获取入口集
.map(Stream :: )
.orElseGet(Stream :: empty)
//我想继续使用
.filter(e - > e.getKey()。startsWith(f)
.map(Entry :: getValue)
.findFirst();

但后来我得不到 Stream< Entry> 但是 Stream< Set< Entry>> ...有没有以某种方式flatMap一个集合或地图的方式吗?



注意:我对这里流畅,纯粹的流/可选方法感兴趣。当然,当我首先将地图保存到local var并确保它不为空。


解决方案

你的错误就在这一行:

  .map( Stream :: of)

函数获取单个参数(或vararg参数),并返回仅包含该元素的流。因此,您将获得流< Set< Map.Entry>> 。相反,你应该在entryset上调用stream方法,如下所示:

  .map(Set :: stream)


I get a map from a service not under my control that might be null and want to process it, let's say, filter, map and reduce to a single element I need.

Question: is there a "link" from Optional to Stream?

I tried (among other things):

 return Optional.ofNullable(getMap())
   .map(Map::entrySet) // gets the entryset
   .map(Stream::of)
   .orElseGet(Stream::empty)
   // i would then like to continue with
   .filter(e -> e.getKey().startsWith("f")
   .map(Entry::getValue)
   .findFirst();

but then I get not Stream<Entry> but Stream<Set<Entry>> ... is there a way to somehow flatMap a collection or map out of an Optional?

Note: I am interested in a fluent, pure stream/optional approach here. It works of course when I save the map to local var first and make sure it is not null.

解决方案

Your mistake is in this line:

.map(Stream::of)

The of function takes a single parameter (or a vararg parameter), and returns a stream with only that element. You will therefore get a Stream<Set<Map.Entry>>. Instead, you should call the stream method on the entryset, like this:

.map(Set::stream)

这篇关于使用基于Optional&lt; Map&gt;的内容的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆