List操作

List操作

Lambda 表达式

Lambda 表达式的语法格式:

  1. (parameters) -> expression
  2. (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方法

foreach

1
2
3
4
// 设置list每一项的值
list.forEach(item->{
item.setUser("lvjie");
})

filter

1
2
3
4
// 过滤输出符合年龄大于21岁的list
list.stream().filter(item ->{
item.getAge > 21
}).collect(Collectors.toList());

map

1
2
// 抽取list每一项中的id组成新的list
list.stream().map(item => item.id).collect(Collectors.toList());

contains

1
2
// 列表包含字符串返回true
list.contains("lvjie")

some

1
2
3
4
// 列表里如果有一项的年龄大于21就返回true
list.stream().some(item -> {
item.getAge > 21
}).collect(Collectors.toList());

every

1
2
3
4
// 列表里每一项的年龄都大于21才返回true
list.stream().every(item->{
item.getAge > 21
}).collect(Collectors.toList());

reduce

1
2
3
4
5
let list = [1, 2, 3, 4];
// 第一参数为数组中的每一项累加和,初始为数组第一项,第二参数为数组的每一项,初始为数组第二项
list.stream().reduce((total, item) ->{
return total + item;
}).collect(Collectors.toList()); // 10

collect

1
2
// 收集流中的数据到list
List<String> list = stream.collect(Collectors.toList());

List操作

作者

lvjie

发布于

2022-06-18

许可协议


:D 一言句子获取中...