Java 8 Lsit和Map之间转化-代码示例

1、List<T>转Map<S,List<T>>

        Map<String, List<Entity>> demoMap = demoList.stream()
                .collect(Collectors.groupingBy(Entity::getkey));  // the type of demoList is List<Entity>

Entity实例getkey()方法返回的值则作为map的key,即按该字段给demoList分类。

2、Map<S,List<T>>转List<T>

        List<Entity> demoList = refDataMap.entrySet().stream()
                .flatMap(map -> map.getValue().stream())
                .collect(Collectors.toList());  //the type of refDataMap is Map<S,List<Entity>>

3、List<T>转Map<S,T>

       Map<String,Entity> map = stats.stream().collect(Collectors.toMap(Entity::getKey,
                c -> c));
       Map<String,String> map = stats.stream().collect(Collectors.toMap(Entity::getKey,
                Entity::getStringValue));   //the type of stats if List<Entity>


——未完待续———


    原文作者:toocarrie
    原文地址: https://blog.csdn.net/u013174217/article/details/53503737
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞