一、前言
利用java8的新特性stream流进行List的转换操作 - 将List<Map<String,Object>> 和 List<Person>转换为 List<String> 。
二、代码示例
1)List<Map<String,Object>>转换为 List<String>代码
package com.xwood.demo.java8;@b@@b@import java.util.ArrayList;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.stream.Collectors;@b@@b@public class MapTest {@b@@b@ public static void main(String[] args) {@b@ //1.@b@ List<Map<String,Object>> mapList = new ArrayList<>();@b@ Map<String,Object> map = new HashMap<>();@b@ map.put("1a","1");@b@ mapList.add(map);@b@ Map<String,Object> map2 = new HashMap<>();@b@ map2.put("1a","1");@b@ map2.put("2a","2");@b@ mapList.add(map2);@b@ Map<String,Object> map3= new HashMap<>();@b@ map3.put("3a","3");@b@ mapList.add(map3);@b@ @b@ List<String> a1List = mapList.stream()@b@ .map(s -> String.valueOf(s.get("1a")))@b@ .collect(Collectors.toList());@b@ System.out.println("示例1:"+a1List);@b@ @b@ @b@ List<String> allList = mapList.stream()@b@ .map(s -> s.entrySet().iterator().next().getKey())@b@ .collect(Collectors.toList());@b@ System.out.println("示例2:"+allList);@b@ @b@ //3.@b@ List<Person> persinList=new ArrayList<Person>(3){{@b@ add(new Person("张三",25));@b@ add(new Person("李四",30));@b@ add(new Person("王五",40));@b@ }};@b@ Map<String,Integer> nameAgeMapping = persinList.stream().collect(Collectors.toMap(Person::getName, Person::getAge));@b@ System.out.println("示例3:"+nameAgeMapping);@b@ @b@ @b@ @b@ }@b@}
运行结果如下
示例1:[1, 1, null]@b@示例2:[1a, 1a, 3a]@b@示例3:{李四=30, 张三=25, 王五=40}
2) 将List<Person>转换为 List<String> 代码
package com.xwood.demo.java8;@b@@b@import com.xwood.demo.optional.User;@b@@b@import java.util.ArrayList;@b@import java.util.List;@b@import java.util.stream.Collectors;@b@@b@public class DtoListTest {@b@@b@ public static void main(String[] args) {@b@ List<Person> peopleList=new ArrayList<Person>(){{@b@ add(new Person("张三",21));@b@ add(new Person("李四",22));@b@ }};@b@@b@ List<String> strList=peopleList.stream().map(Person::getName).collect(Collectors.toList());@b@ System.out.println(strList);@b@ }@b@@b@@b@}
运行结果
[张三, 李四]@b@