当前位置: 首页 > news >正文

Lambda表达式总结

Lambda作为Java8的新特性,本篇文章主要想总结一下常用的一下用法和api

1.接口内默认方法实现

public interface Formula {double calculate(int a);// 默认方法default double sqrt(int a) {return Math.sqrt(a);}
}
public static void main(String[] args) {Formula formula = new Formula() {@Overridepublic double calculate(int a) {return sqrt(a * 100);}};double a1 = formula.calculate(100);double b1 = formula.sqrt(16);System.out.println(a1); // 100.0System.out.println(b1); // 4.0
}

2.lambda表达式

List<String> names = Arrays.asList("peter", "anna", "xenia", "mike");
// 老版本
Collections.sort(names, new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o2.compareTo(o1);}
});// lambda写法
Collections.sort(names, (o1, o2) -> o2.compareTo(o1));
// 更简易的写法
names.sort((a,b) ->  b.compareTo(a));
System.out.println(names);

3.函数式接口(Funcation Interface)

java8中:: 关键字引用构造方法,对象方法和静态方法

// 定义: 仅仅包含一个抽象方法的接口, @FunctionalInterface只是一个标识,有没有都可以
// 只有函数式接口才能写成lambda表达式
@FunctionalInterface
public interface Convert<T, R> {R convert(T from);
}// :: 使用关键字来引用类的方法或者构造器
Convert<String, Integer> convert = Integer::valueOf; // 引用静态方法
Integer convert1 = convert.convert("123");
System.out.println(convert1);String s = "hello";
Convert<Integer, String> convert2 = s::substring; // 引用构造方法
String convert3 = convert2.convert(1);
System.out.println(convert3);
Convert<String, String> convert5 = String::new; // 引用构造方法
System.out.println(convert5);
// 定义了一个函数式接口PersonFactory
public interface PersonFactory<P extends Person> {P create(String firstName, String lastName);
}class Person {String firstName;String lastName;Person() {}Person(String firstName, String lastName) {this.firstName = firstName;this.lastName = lastName;}@Overridepublic String toString() {return "Person{" +"firstName='" + firstName + '\'' +", lastName='" + lastName + '\'' +'}';}
}
// 将Person的构造函数作为函数式接口的实现
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("peter", "parker");
System.out.println(person);

4.lambda访问外部变量及接口默认方法

// 定义一个函数式接口
@FunctionalInterface
public interface Convert<T, R> {R convert(T from);
}// 由于Convert是函数式接口,所以可以写成lambda,也就是说可以作为lambda表达式的类型
int num = 1; // num被用在了lambda内,必须为final类型,这里没写是因为是隐式的final类型
Convert<Integer, String> convert4 = (from -> String.valueOf(from + num));
String result = convert4.convert(2);
System.out.println(result);// 访问接口默认方法
@FunctionalInterface
public interface Formula {double calculate(int a);default double sqrt(int a) {return Math.sqrt(a);}
}// 匿名内部类的访问方式
Formula formula = new Formula() {@Overridepublic double calculate(int a) {return sqrt(a * 100);}
};
double a1 = formula.calculate(100);
double b1 = formula.sqrt(16);
System.out.println(a1);
System.out.println(b1);
// Formula formula = (a) -> sqrt(a * 100); 这个可不行,会编译报错

5.内置的函数式接口

5.1 Predicate断言

Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test("")); // true
Predicate<String> predicate = (s) -> s.length() > 0;
System.out.println(predicate.test("foo"));              // true
// 返回test()取反的结果
System.out.println(predicate.negate().test("foo"));     // false

5.2 Funcation

Function<String, Integer> function = Integer::valueOf;
// 将两个function组合起来, 先执行function在将function的输出作为输入计算x + 3最终输出结果
Function<String, Integer> function1 = function.andThen(x -> x + 3);
System.out.println(function1.apply("123"));// compose, 从右往左执行
Function<Integer, Integer> addFunction = x -> x + 1;
Function<Integer, Integer> multiplyByTwo = x -> x * 2;
Function<Integer, Integer> square  = x -> x * x;
Function<Integer, Integer> compose = addFunction.compose(multiplyByTwo).compose(square);
Integer apply = compose.apply(1);
System.out.println(apply); // 3

5.3 Supplier 生产者

// 不接收任何参数,直接返回一个指定的结果
Supplier<String> supplier = String::new;
String s1 = supplier.get(); // new String();
// 直接返回一个Person对象
Supplier<Person> supplier1 = Person::new;
Person person1 = supplier1.get();
System.out.println(person1);

5.4 Consumer消费者

// 提供入参 以供消费
Consumer<String> consumer = (p) -> System.out.println(p + " hello world!");
consumer.accept("123"); // 123 hello world!

5.5 Comparator

Comparator<Integer> comparator = (x1, x2) -> x1.compareTo(x2);
int compare = comparator.compare(1, 2);
System.out.println(compare); // 相等返0, 第一个参数 > 第二个参数返回1, 否则返回-1

6 Stream流

List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");

6.1 Filter过滤

// filter()
stringCollection.stream().filter((s3) -> s3.startsWith("a")).forEach(System.out::println);

6.2 Sorted 排序

// sorted()
stringCollection.stream().sorted().filter((s3) -> s3.startsWith("a")).forEach(System.out::println);

6.3 Map转换

// map()
stringCollection.stream().map(String::toUpperCase).sorted(String::compareTo).forEach(System.out::println);

6.4 Match匹配

// match()
boolean match = stringCollection.stream().anyMatch(s3 -> s3.startsWith("a"));
// 验证stringCollection中是否都不是以a开头
boolean match2 = stringCollection.stream().noneMatch(s3 -> s3.startsWith("a"));
boolean match3 = stringCollection.stream().allMatch(s3 -> s3.startsWith("a"));
System.out.println(match); // true
System.out.println(match2); // false
System.out.println(match3); // false

6.5 Count计数

// count()
long count = stringCollection.stream().filter(s3 -> s3.startsWith("a")).count();
System.out.println(count); // 2

6.6 Reduce

// reduce, 将多个元素归约成一个值
stringCollection.stream().sorted().reduce((s4, s5) -> s4 + "#" + s5).ifPresent(System.out::println);
http://www.lryc.cn/news/111938.html

相关文章:

  • 岛屿的最大面积
  • 迭代器模式(Iterator)
  • Goland搭建远程Linux开发
  • react中PureComponent的理解与使用
  • 洛谷——P5714 【深基3.例7】肥胖问题
  • Mac隐藏和显示文件
  • 软件工程中应用的几种图辨析
  • 下载离线版的VS Visual Studio 并下载指定的版本
  • Eureka 学习笔记5:InstanceRegistry
  • System Verilog——虚方法的使用
  • 线性规划和单纯形法-原理篇
  • FBX SDK开发快速上手指南
  • 探讨|使用或不使用机器学习
  • Git笔记--Ubuntu上传本地项目到github
  • 基于Go编写一个可视化Navicat本地密码解析器
  • Maven【入门笔记】
  • Android Studio中使用cmake开发JNI实战
  • 第七章 图论
  • IEEE SystemVerilog Chapter13 : Tasks and functions (subroutines)
  • day39反转字符串总结
  • 使用Socket实现TCP版的回显服务器
  • 【Nacos篇】Nacos基本操作及配置
  • Dockerfile构建Tomcat镜像
  • k8s的介绍
  • mysql sql语句 需要使用like 场景,解决方案
  • 通过C语言设计的贪吃蛇游戏(控制台终端)
  • c++实现Qt信号和槽机制
  • 【Linux】五、进程
  • 使用 OpenCV 和 Python 卡通化图像-附源码
  • GitLab不同角色对应的权限