map 函数的作用就是针对管道流中的每一个数据元素进行转换操作。
例如
将集合中的每一个字符串,全部转换成大写!
List < String > collect = alpha. stream ( ) . map ( String :: toUpperCase ) . collect ( Collectors . toList ( ) ) ;
直接返回各个元素的长度生成一个新的数组,也就是说不仅可以处理数据,还可以在处理数据的过程中转换数据类型
List < String > alpha = Arrays . asList ( "Monkey" , "Lion" , "Giraffe" , "Lemur" ) ;
List < Integer > lengths = alpha. stream ( ) . map ( String :: length ) . collect ( Collectors . toList ( ) ) ; System . out. println ( lengths) ;
处理对象数据
public static void main ( String [ ] args) { Employee e1 = new Employee ( 1 , 23 , "M" , "Rick" , "Beethovan" ) ; Employee e2 = new Employee ( 2 , 13 , "F" , "Martina" , "Hengis" ) ; Employee e3 = new Employee ( 3 , 43 , "M" , "Ricky" , "Martin" ) ; Employee e4 = new Employee ( 4 , 26 , "M" , "Jon" , "Lowman" ) ; Employee e5 = new Employee ( 5 , 19 , "F" , "Cristine" , "Maria" ) ; Employee e6 = new Employee ( 6 , 15 , "M" , "David" , "Feezor" ) ; Employee e7 = new Employee ( 7 , 68 , "F" , "Melissa" , "Roy" ) ; Employee e8 = new Employee ( 8 , 79 , "M" , "Alex" , "Gussin" ) ; Employee e9 = new Employee ( 9 , 15 , "F" , "Neetu" , "Singh" ) ; Employee e10 = new Employee ( 10 , 45 , "M" , "Naveen" , "Jain" ) ; List < Employee > employees = Arrays . asList ( e1, e2, e3, e4, e5, e6, e7, e8, e9, e10) ; List < Employee > maped = employees. stream ( ) . peek ( e -> { e. setAge ( e. getAge ( ) + 1 ) ; e. setGender ( e. getGender ( ) . equals ( "M" ) ? "male" : "female" ) ; } ) . collect ( Collectors . toList ( ) ) ; System . out. println ( maped) ; }