Java8的stream().map()用法详解
作者:程序员阿斌
这篇文章主要介绍了Java8的stream().map()用法详解,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java8的stream().map()用法
在Java编码过程中可能会遇到这个场景
遍历一个列表,对列表中的属性进行转换、赋值等操作形成我们想要的一个新列表。通常我们的常规思路就是直接使用for循环。
在Java8引入lambda表达式后我们可以使用stream流链式处理的方式,形成新流来达到预期效果。
stream操作比较多,这里主要针对map()
举出下面三个列子
体验stream().map().collect(Collectors.toList())对于集合元素处理的用法。
package com.base.labguage.java8; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamMap { private static class People{ private String name; private Integer age; private String address; // 只给出构造方法,忽略get/set细节 public People(String name, Integer age, String address) { this.name = name; this.age = age; this.address = address; } } public static class PeoplePub{ private String name; private Integer age; // 只给出构造方法,忽略get/set细节 public PeoplePub(String name, Integer age) { this.name = name; this.age = age; } // 重写toString方法 public String toString(){ return "(" + this.name + "," + this.age + ")"; } } public static void main(String[] args) { List<People> peoples = Arrays.asList( new People("zs", 25, "cs"), new People("ls", 28, "bj"), new People("ww", 23, "nj") ); // List -> String List<String> names = peoples.stream().map(p -> p.getName()).collect(Collectors.toList()); // stream流实现英文字母转大写 List<String> upNames = names.stream().map(String::toUpperCase).collect(Collectors.toList()); // stream流实现数字乘倍数 List<Integer> ages = peoples.stream().map(p -> p.getAge() * 2).collect(Collectors.toList()); // list - > new List List<PeoplePub> peoplePubs = peoples.stream().map(p -> { return new PeoplePub(p.getName(), p.getAge()); }).collect(Collectors.toList()); System.out.println("to print upnames List : " + upNames); System.out.println("to print ages List : " + ages); System.out.println("to print new people List" + peoplePubs.toString()); } }
控制台打印结果:
to print upnames List : [ZS, LS, WW]
to print ages List : [50, 56, 46]
to print new people List[(zs,25), (ls,28), (ww,23)]
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。