1

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>>. 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

from How to convert List<NameValuePair> into a 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.

Languoguang
  • 2,166
  • 2
  • 10
  • 15

2 Answers2

3

You can convert each NameValuePair into Map.Entry and then collect them into List

List<Map.Entry<String, String>> entries = list.stream()
                                              .map(n->new AbstractMap.SimpleEntry<String, String>(n.getName(), n.getValue())
                                              .collect(Collectors.toList());
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

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";
    }
}
stackguy
  • 188
  • 5