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

来源:互联网 发布:淘宝 手机店 编辑:程序博客网 时间:2024/05/21 17:32

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>


------未完待续---------


0 0
原创粉丝点击