java8 httpclient NameValuePair转换14行代码一行搞定!

版权声明:本文为博主原创文章,转载请加入源链接。 https://blog.csdn.net/kevin_mails/article/details/82014584

工作中,我们常常会通过httpclient调用一些三方提供的api, 进行参数传递的时候会用NameValuePair[ ]

于是我们同事写了一个方法封装一下 NameValuePair,将map中用  参数key ,参数值value,做一个转换

如下:

public static NameValuePair[] convertMap2NameValuePairs(Map<String, String> data) {
        Set<Map.Entry<String, String>> entrySet = data.entrySet();
        int size = entrySet.size();
        NameValuePair[] nameValuePairs = new NameValuePair[size];
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            NameValuePair nameValuePair = new NameValuePair(key, value);
            nameValuePairList.add(nameValuePair);
        }
        for (int i = 0; i < nameValuePairList.size(); i++) {
            nameValuePairs[i] = nameValuePairList.get(i);
        }
        return nameValuePairs;
    }

看了上面的代码,觉得写的太长,用java8 写了一个简化版的,一行代码。如下:

public static NameValuePair[] convertMap2NameValuePairs(Map<String, String> data) {
        return data.entrySet().stream().map(entry -> new NameValuePair(entry.getKey(), entry.getValue())).toArray(NameValuePair[]::new);
    }

java8 的新特性确实可以让代码变得更加简洁,值得我们去学习和使用!

猜你喜欢

转载自blog.csdn.net/kevin_mails/article/details/82014584