Java8 stream().map() 是一个中间操作,可实现对元素进行修改,这意味着它返回Stream对象。
代码实现:
package com.collectStream;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TestStreamMap {
public static void sorted() {
List<Integer> list = Arrays.asList(5, 4, 3, 2, 7, 1, 6, 0, 8);
List<Integer> newList = list.stream().map(x -> x + 1).collect(Collectors.toList());
System.out.println("原始数组:" + list);
System.out.println("自增一后:" + newList);
System.out.println();
List<Student> personList = new ArrayList<>();
personList.add(new Student("张三", 16, 181));
personList.add(new Student("李四", 17, 180));
personList.add(new Student("王五", 16, 179));
personList.add(new Student("张明", 18, 177));
personList.add(new Student("李威", 16, 190));
personList.add(new Student("王鹏", 15, 188));
personList.add(new Student("王莉", 17, 177));
//筛选年龄大于15岁,年龄升序,并定义为合格
List<Student> qualifiedPList = personList.stream()
.filter(student -> student.getAge() > 15)
.sorted(Comparator.comparingInt(Student::getAge))
.map(student -> {
student.setFlag("合格");
return student;
})
.collect(Collectors.toList());
printStudents(qualifiedPList);
}
public static void printStudents(List<Student> StudentList) {
System.out.println("【姓名】\t【年龄】\t【身高】\t【审核】");
System.out.println("-------------------------------");
StudentList.forEach(s -> System.out.println(s.toString()));
System.out.println(" ");
}
public static void main(String[] args) {
sorted();
}
}
@Data
class Student {
private String name;
private Integer age;
private Integer height;
private String flag;
public Student(String name, Integer age, Integer height) {
this.name = name;
this.age = age;
this.height = height;
}
public String toString() {
String info = String.format("%s\t\t%s\t\t%s\t\t%s\t\t\t", this.name, this.age.toString(), this.height.toString(), this.getFlag());
return info;
}
}
打印输出:
原始数组:[5, 4, 3, 2, 7, 1, 6, 0, 8]
自增一后:[6, 5, 4, 3, 8, 2, 7, 1, 9]
【姓名】 【年龄】 【身高】 【审核】
-------------------------------
张三 16 181 合格
王五 16 179 合格
李威 16 190 合格
李四 17 180 合格
王莉 17 177 合格
张明 18 177 合格
|