【JAVA】由一个将JSONArray转成Map的需求引发的lambda语法的学习

时间:2019-04-06 00:43:47   收藏:0   阅读:461

在写代码时总是遇到将JSONArray转成Map的需求,想要用java8的lambda表达式去编写,发现网上没有类似的参考答案,无果自己耐心的学了下函数式编程,完美解决了这个问题
网上大多数代码都是这样的,截取片段如下

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity()));
}

一、问题

针对的是List其元素为对象的转换,不符合自我需求,JSONArray 元素是Object

二、解决

public void testStream(){
        JSONObject ecsInstanceList = productInstance.getEcsInstanceList();
        JSONArray ecsArr = ecsInstanceList.getJSONObject("data").getJSONArray("result") ;
        
        Map<String, Object> collect = ecsArr.stream().collect(Collectors.toMap(i -> {JSONObject a= (JSONObject)i;String k = a.getString("instanceId");return k;} , Function.identity()));
        System.out.println(collect);
    }

三、解释

 * @param <T> the type of the input elements
 * @param <K> the output type of the key mapping function
 * @param <U> the output type of the value mapping function
 * @param keyMapper a mapping function to produce keys
 * @param valueMapper a mapping function to produce values
public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
    }
static <T> Function<T, T> identity() {
        return t -> t;
    }

这样看你会发现它是静态方法,所以是Function.的方式创建,这个方法将返回一个函数式接口,接口特殊之处在于t -> t,意思就是输入什么内容输出便是什么内容,这样Function.identity() 参数也可以换成 v -> v,一个道理

原文:https://www.cnblogs.com/jzsg/p/10660514.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!