java8 .stream().filter() 代替for循环 lambda表达式

先说一下lambda表达式:
lambda 表达式的语法格式如下:
(parameters) -> expression

(parameters) ->{ statements; } //或者这种
Lambda 表达式的简单例子:
// 1. 不需要参数,返回值为 5
() -> 5

// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x

// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y

// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y

// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)
再说一下list.stream().filter():
Employee.java
public class Employee {
private Integer id;
private Integer age;
private String gender;
private String firstName;
private String lastName;

public Employee(Integer id, Integer age, String gender, String fName, String lName) {
this.id = id;
this.age = age;
this.gender = gender;
this.firstName = fName;
this.lastName = lName;
}

@Override
public String toString() {
return this.id.toString() + " - " + this.age.toString()+"\n";
}

//get,set省略...
}
TestEmployeePredicates.java
public class TestEmployeePredicates {
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 = new ArrayList<Employee>();
employees.addAll(Arrays.asList(new Employee[] { e1, e2, e3, e4, e5, e6, e7, e8, e9, e10 }));

//代码如下
}
}
1.输出符合表达式的每一个对象
employees.stream().filter(p -> p.getAge() > 21).forEach(System.out::println);
//输出每一个对象
2.返回一个符合表达式的集合
employees.stream().filter(predicate).collect(Collectors.<Employee>toList());
//返回一个集合
3.返回符合表达式的集合的第一个对象
employees.stream().filter(p -> p.getAge() > 21).findFirst();
4.抽取对象中所有的id的集合
employees.stream().map(Employee::getId).collect(Collectors.toList());

posted @ 2021-10-28 18:44  旧巷里的旧少年  阅读(1025)  评论(0编辑  收藏  举报