如何使用Java 8 Streams迭代键值?

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

How to using Java 8 Streams to iterate over key values?

问题

String products = UtlityToReadValueFromProperties.get("financialProducts");
List<String> list = Arrays.asList(products.split(","));
String result = list.stream()
    .map(item -> UtlityToReadValueFromProperties.get(item))
    .filter(value -> value.contains("OPM"))
    .findFirst()
    .orElse("EQUITY");

这段代码会从 properties 文件中读取 financialProducts 的值,然后将其拆分为列表。接下来,它会迭代这个列表,对每个值调用 UtlityToReadValueFromProperties.get(item) 来获取对应的值。然后,它会使用 filter 来查找包含 "OPM" 的值,如果找到,就返回该值,否则返回 "EQUITY"。

英文:

I want to write a program for below pseudocode using java 8 streams

read an entry from a properties file
if value contains "input" return the field
I have a utility that reads from the properties file.

financialProducts=FX,EQUITY
FX=ABC,LMN,XYZ
EQUITY=OPM,PWZ,TYU

if I have to read financialProducts and iterate through FX, EQUITY
when iterating though values of FX, if values contain PWZ, I must return FX else iterate through EQUITY and look for value PWZ in it.

This is what I have so far

 String products = UtlityToReadValueFromProperties.get(&quot;financialProducts&quot;); 
 List&lt;String&gt; list = Arrays.asList&lt;names.split(&quot;,&quot;); 
 String result = list.stream().map(item -&gt; UtlityToReadValueFromProperties .get(item)).filter(value -&gt; values.contains(&quot;OPM&quot;).toString();
// This return OPM,PWZ,TYU, however, I want the code to return EQUITY

答案1

得分: 1

尝试使用这个流:

 String result = list.stream().filter(item -&gt; UtlityToReadValueFromProperties.get(item).constains(&quot;OPM&quot;)).toString();

首先,您正在使用列表创建一个流,然后我们按如下方式过滤值,对于每个项:

> 1) 我们使用UtlityToReadValueFromProperties.get获取属性的值。
> 2) 我们检查给定的值,
> 在这里是"OPM",是否存在于所选属性的值之间。
> 3) 如果"OPM"存在于属性值中,则该项名称将与过滤结果列表一起返回。

英文:

Try with this stream instead:

 String result = list.stream().filter(item -&gt; UtlityToReadValueFromProperties.get(item).constains(&quot;OPM&quot;)).toString();

First, you are creating a stream using your list, then we filter throw the values as follows, for each item:

> 1) We get the value of the property using
> UtlityToReadValueFromProperties.get.
> 2) We check if the given value,
> here "OPM", exists between the values of the selected property.
> 3) If the "OPM" exists in the property values, it item name will be returned with the list of filter results.

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

发表评论

匿名网友

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

确定