Java 8 Lsit和Map之間轉化-程式碼示例
阿新 • • 發佈:2019-01-30
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>