lambda表达式简单使用

1. lambda基本语法

(parameters) -> expression 或 (parameters) ->{ statements; }
例如:

// 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)

2.Stream

stream是集合的包装,通常可以一起同lambda表达式一起使用。可以支持很多操作:map,filter,sorted,count,max,min,sum,collect等。

3. lambda + stream

创建测试类:

@Data
class Person {
  private String firstName;
  private String lastName;
  private String gender;
  private String job;
  private int age;
  private int salary;
}

向personList插入数据,使用lambda输出所有person信息:

personList.forEach((person) -> System.out.println(person.firstName + person.lastName));

显示月薪超过14k的person信息:

personList.stream()
        .filter((p) -> (p.salary > 14))
        .forEach((person) -> System.out.println(person.firstName + person.lastName));

将person信息中的firstName存入到set中:

set<String> firstNameSet = personList.stream()
                                  .map(Person::getFirstName)
                                  .collect(toSet());

猜你喜欢

转载自www.cnblogs.com/isshpan/p/12785025.html