// 将实体类的list,转换为map
List<User> userList = new LinkedList<>();
Map<Integer,User> userMap = userList.
stream().
collect(Collectors.toMap(
item -> item.getId(),// 操做map的key
item-> item,// 操做map的value
(v1,v2)->v1
));
// 更简单的方式
Map<Integer,User> userMap1 = userList.
stream().
collect(Collectors.toMap(
item -> item.getId(),// 操做map的key
Function.identity()));// 适用于map的value是item的自己
// List<Integer> -> List<String>
List<Integer> sourceList = new ArrayList<>();
List<String> targetList = sourceList.stream().
map(String::valueOf).collect(Collectors.toList());
// List<String> -> List<Integer>
List<String> sourceList = new ArrayList<>();
List<Integer> targetList = sourceList.stream().
map((str -> Integer.parseInt(str))).collect(Collectors.toList());
// List<String> 与 String转换
List<String> sourceList = new ArrayList<>();
String targetStr = String.join(",",sourceList );// 第一个参数为造成字符串后的链接符
// String 与 List<String>转换
List<String> targetList = Arrays.asList(targetStr.split(","));// 参数为字符串的链接符
// 注意:以上代码为伪代码,实际操做时应注意非空验证
// 对比串行与并行的效率(stream/parallelStream)
List<Integer> intList = new ArrayList<>();
for(int i=0;i<100000;i++) {
intList.add(i);
}
long t1 = System.currentTimeMillis();
List<String> collect = intList.stream().map(integer1 -> integer1 + "key").collect(Collectors.toList());
long t2 = System.currentTimeMillis();
List<String> collect1 = intList.parallelStream().map(integer1 -> integer1 + "key").collect(Collectors.toList());
long t3 = System.currentTimeMillis();
System.out.println("---串行:"+(t2-t1));//---串行:38
System.out.println("---并行:"+(t3-t2));//---并行:17