繁体   English   中英

使用带过滤器的 map 和 stream 时如何加入

[英]How to join when using map with filter with stream

如果getData()返回"yes" ,我想创建一个查询。 所以添加了相同的过滤器。

现在,如果getData()的值为"yes" ,那么我想连接我从 object 获得的三个参数。

现在对于 object 的列表,我想加入所有来自的值

(f -> f.getF()+" "+f.getO()+" "+f.getV())

用“和”作为分隔符,但无法弄清楚。

String query = data.stream()
    .filter(f -> f.getData().equalsIgnoreCase("yes"))
    .map(f -> f.getF()+" "+f.getO()+" "+f.getV())
    .collect(Collectors.joining(" and","how to do this" , suffix));

例如,我们从 object 获取数据为

f.getF()--------"列名"

f.getO()--------"="

f.getV()--------"2"

所以我想用和分隔符添加所有条件,并生成一个包含所有条件的字符串。

我想我可以 append "and" 在 map() 中,然后从字符串中删除最后一个 "and"

像这样的东西

columnname = 2 和 columnnam1 > 1 和 column2 = 6

如果F是列名, O是运算符, V是值,如果您需要获取column1 = 1 and column2 > 2 and...那么您只需要使用Collectors.joining(" and ")

String query = data.stream() // stream1 - original stream of the data collection
    .filter(f -> f.getData().equalsIgnoreCase("yes")) // stream2 - contains only elements with "yes"
    .map(f -> f.getF()+" "+f.getO()+" "+f.getV()) // stream3 - stream of the strings produced by expression f.getF()+" "+f.getO()+" "+f.getV()
    .collect(Collectors.joining(" and "));

一些解释。 这里.collect(Collectors.joining(...))加入了前面的.map(f -> f.getF()+" "+f.getO()+" "+f.getV())调用。

创建了 3 个不同的流:

String query = data.stream() // stream1 - original stream of the data collection
    .filter(f -> f.getData().equalsIgnoreCase("yes")) // stream2 - contains only elements with "yes"
    .map(f -> f.getF()+" "+f.getO()+" "+f.getV()) // stream3 - stream of the strings produced by expression f.getF()+" "+f.getO()+" "+f.getV()
    .collect(Collectors.joining(" and","how to do this" , suffix));

所以,首先你加入f.getF()f.getO()f.getV()" "连接器如下:

.map(f -> f.getF()+" "+f.getO()+" "+f.getV())

你会得到像这样的字符串的 stream

"F1 O1 V1",
"F2 O2 V2",
...

Tis stream 将加入.collect(Collectors.joining(...)); . 例如,使用.collect(Collectors.joining(" and ")); 会产生类似的字符串

"F1 O1 V1 and F2 O2 V2 and ..."

你几乎在那里:

String query = data.stream()
    .filter(f -> f.getData().equalsIgnoreCase("yes"))
    .map(f -> f.getF() + " " + f.getO() + " " + f.getV()))
    .collect(Collectors.joining(" and "));

这将产生如下内容:

columnName1 = 2 and columnName2 > 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM