Java Lambda!

系列主要回顾总结Lambda表达式。

定义

说白了,Lambda表达式通过表达式来替代接口功能。表达式就像方法一样,有两部分组成,参数列表和使用参数的主体。“函数式接口”是指仅仅只包含一个抽象方法的接口。

1
(parameters) -> expression

普通用法

1
2
3
4
5
6
7
8
9
10
11
12
1.
Map<String, String> maps = new HashMap<>();
maps.keySet().forEach(tempName -> System.out.println(tempName));
maps.values().forEach(tempName -> System.out.println(tempName));

2.
Student s1 = new Student(27, "Rocka");
Student s2 = new Student(25, "Rain");

Comparator<Student> comparator = (x, y) -> Integer.compare(s1.getAge(), s2.getAge());
int result = comparator.compare(s1, s2);
System.out.println("lambda比较结果为: " + result);

双冒号

1
2
3
4
5
6
7
8
9
10
11
//1.普通
for (String s : strs) {
System.out.println("output:" + s);
}
//2.Lambda
strs.forEach(x -> System.out.println(x));
//3.双冒号
strs.forEach(Lambda_2::printStr);
//4.另外一种写法
Consumer<String> methodParams = Lambda_2::printStr;
strs.forEach(methodParams);

Stream

Stream主要用于集合而言,对于数组是没有效果的,Stream其实就是一个Iterator的再包装。

举个栗子:

1
nums.stream().filter(nums -> nums != null).collect();
  • nums.stream(): 这一部分是代表集合转换为Stream流.
  • .fiter(): 这一部分代表Stream流转换为另一部分Stream流,剔除掉了为空的部分.
  • .collect(): 这一部分代表将转换后的流收集起来

Stream的常用方法

常用方法,这里不一一赘述

  • distinct: 去重复数据
  • filter: 过滤数据,新生成的只是符合条件的
  • skip: 丢弃原stream前n个元素
  • limit: 获取前n个元素
  • peek: 接收一个没有返回值的λ表达式,可以做一些输出,外部处理等
  • flatMap: Function表示接收一个参数,并产生一个结果的函数

列举常用的用法

  • Map用来筛选成为合逻辑的Map

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
      Map<Integer, Integer> s = new HashMap<>();
    s.put(3, 3);
    s.put(3, 20);
    s.put(4, 4);
    s.put(7, 15);
    s.put(33,20);

    Map<Integer, Integer> finalM;
    finalM = s.entrySet().stream().filter(a -> a.getValue() > 10).map(a -> a.getKey()).collect(Collectors.toMap(Integer::intValue, a -> s.get(a.intValue())));
    System.out.println(finalM);

Demo地址

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器