[英]Java 8 stream api control output
I have the following code. 我有以下代码。
List<String> parseAttribValueByTag(String tag, String attrib, List<String> attribName) throws IOException {
List<String> keys = new ArrayList<>();
Document doc = Jsoup.connect(url).get();
Elements inputs = doc.select(tag + "[" + attrib + "]");
for (String item : attribName) {
System.out.println(inputs.stream()
.filter(input -> input.attr("name").contains("__VIEWSTATE"))
.findFirst());
}
return keys;
}
It gives me the following output 它给了我以下输出
Optional[<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="5ue/NxnSLQ2akzQo5R8wBEZ,,."
I would like to control the output so it only gives me __VIEWSTATE "5ue/NxnSLQ2akzQo5R8wBEZ,,."
我想控制输出,所以它只给我
__VIEWSTATE "5ue/NxnSLQ2akzQo5R8wBEZ,,."
I've tried using .map(input -> input.attr("value"))
and it gives me Optional[5ue/NxnSLQ2akzQo5R8wBEZ,,.
我尝试过使用
.map(input -> input.attr("value"))
,它给了我Optional[5ue/NxnSLQ2akzQo5R8wBEZ,,.
but when I add an additional .map(input -> input.attr("name"))
to also give me the name I get the following error " Cannot resolve method 'attr(java.lang.String)' ". 但是当我添加一个额外的
.map(input -> input.attr("name"))
也给我这个名字时,我得到以下错误“ 无法解析方法'attr(java.lang.String)' ”。 What is it I'm doing wrong in the code? 我在代码中做错了什么? Is there a way around it?
有办法解决吗?
If you add a .map(input -> input.attr("value"))
, you convert your Stream
to a Stream<String>
(assuming that attr
returns a String
), and String
doesn't have an attr
method, so the second map
call doesn't pass compilation (hence the compilation error - Cannot resolve method 'attr(java.lang.String)'
). 如果添加
.map(input -> input.attr("value"))
, .map(input -> input.attr("value"))
Stream
转换为Stream<String>
(假设attr
返回一个String
),而String
没有attr
方法,所以第二个map
调用没有通过编译(因此编译错误 - Cannot resolve method 'attr(java.lang.String)'
)。
You could use a single map
operation to obtain both attributes. 您可以使用单个
map
操作来获取这两个属性。 For example : 例如 :
System.out.println(inputs.stream()
.filter(input -> input.attr("name").contains("__VIEWSTATE"))
.map(input -> input.attr("name") + " " + input.attr("value"))
.findFirst());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.