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());
相关文章
- php之快速入门学习-13(PHP 循环 - While 循环)
- Python for循环的用法,怎么前面还有一个变量或函数?
- js setTimeout 与 setInterval 以及 for 循环 刷新UI
- python 循环(while、for、break、continue、循环嵌套、while...else、for...else)
- 13 python - for循环
- 微信小程序 - wx:for 循环渲染多个 “重复“ 子组件(仅子组件 id 不同,this.selectComponent 使用时依然能准确找到子组件)将子组件 id 设为动态每个子组件都是独立的!
- 增强for循环和普通for循环的区别
- 《R语言数据挖掘:实用项目解析》——第1章,第1.10节循环原理——while循环
- Java中for循环的六种形态
- 【JS】for in循环对象,hasOwnProperty()的作用
- 06 for循环 增强for循环 练习
- python while和for循环用法
- for in 循环
- 浅析List.remove在for循环中会出现的问题及解决方案
- C语言逗号表达式在for循环语句中的使用
- 批处理命令 For循环命令具体解释!
- robot:循环遍历数据库查询结果是否满足要求
- Python的range函数与for循环语句
- c# 并行计算(大量循环处理的场景下)
- JavaScript for...in 循环