[英]How to convert List<NameValuePair> into a List<Map.Entry<String, String>>?
I'm capturing parameters from a request url using com.apache.http.NameValuePair
which basically store those params in a List<NameValuePair>
. I'm capturing parameters from a request url using
com.apache.http.NameValuePair
which basically store those params in a List<NameValuePair>
. To do certain checks and verifications on those params, I need to convert that list into a List<Map.Entry<String, String>>
.要对这些参数进行某些检查和验证,我需要将该列表转换为
List<Map.Entry<String, String>>
。 Is there a way to do this conversion?有没有办法进行这种转换?
something like this:像这样的东西:
http://127.0.0.1:9898/v3/ {project_id}/eip/publicips?fields=id&fields=owner http://127.0.0.1:9898/v3/ {project_id}/eip/publicips?fields=id&fields=owner
from How to convert List<NameValuePair> into a hashMap<String, String>?从如何将 List<NameValuePair> 转换为 hashMap<String, String>?
Map<String, String> mapped = list.stream().collect(
Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
It is not work for me.这对我不起作用。 because there are many fields key.
因为有很多字段键。
You can convert each NameValuePair into Map.Entry and then collect them into List
您可以将每个NameValuePair转换为Map.Entry然后将它们收集到
List
List<Map.Entry<String, String>> entries = list.stream()
.map(n->new AbstractMap.SimpleEntry<String, String>(n.getName(), n.getValue())
.collect(Collectors.toList());
Probably you've messed something else that's not included in the code excerpt.可能您弄乱了代码摘录中未包含的其他内容。 I've tried to reproduce your case and it works in my setup.
我试图重现您的案例,它在我的设置中有效。
public class Main {
public static void main(String[] args) {
List<NameValuePair> list = new ArrayList<>();
MyNameValuePair myNameValuePair = new MyNameValuePair();
myNameValuePair.setKvKey("i");
list.add(myNameValuePair);
myNameValuePair = new MyNameValuePair();
myNameValuePair.setKvKey("j");
list.add(myNameValuePair);
myNameValuePair = new MyNameValuePair();
myNameValuePair.setKvKey("k");
list.add(myNameValuePair);
Map<String, String> mapped = new HashMap<>();
mapped = list.stream().collect(
Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
System.out.println(mapped);
}
}
class MyNameValuePair implements NameValuePair {
private String kvKey;
public void setKvKey(String kvKey){
this.kvKey = kvKey;
}
@Override
public String getName() {
return kvKey;
}
@Override
public String getValue() {
return "val";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.