当前位置:网站首页>【:: 是什么语法?】
【:: 是什么语法?】
2020-11-06 21:19:00 【Mrchai521】
一:简洁
方法引用分为三种,方法引用通过一对双冒号:: 来表示,方法引用是一种函数式接口的另一种书写方式
-
静态方法引用,通过类名::静态方法名, 如 Integer::parseInt
-
实例方法引用,通过实例对象::实例方法,如 str::substring
-
构造方法引用,通过类名::new, 如 User::new
二:方法引用
public final class Integer {
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
}
通过方法引用,可以将方法的引用赋值给一个变量,通过赋值给Function,说明方法引用也是一种函数式接口的书写方式,Lambda表达式也是一种函数式接口,Lambda表达式一般用于自己提供方法体,而方法引用一般直接引用现成的方法。
public class User {
private String username;
private Integer age;
public User() {
}
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
// Getter&Setter
}
public static void main(String[] args) {
// 使用双冒号::来构造静态函数引用
Function<String, Integer> fun = Integer::parseInt;
Integer value = fun.apply("123");
System.out.println(value);
// 使用双冒号::来构造非静态函数引用
String content = "Hello JDK8";
Function<Integer, String> func = content::substring;
String result = func.apply(1);
System.out.println(result);
// 构造函数引用
BiFunction<String, Integer, User> biFunction = User::new;
User user = biFunction.apply("mengday", 28);
System.out.println(user.toString());
// 函数引用也是一种函数式接口,所以也可以将函数引用作为方法的参数
sayHello(String::toUpperCase, "hello");
}
// 方法有两个参数,一个是
private static void sayHello(Function<String, String> func, String parameter){
String result = func.apply(parameter);
System.out.println(result);
}
三:Optional 可选值
在Google Guava 中就有Optional,在Swift语言中也有这样类似的语法,在Swift中将可选值作为一种数据类型,地位和基本类型平齐平做,地位非常高。
/** * @since 1.8 */
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>();
private final T value;
private Optional() {
this.value = null;
}
// 返回一个空的 Optional实例
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
// 返回具有 Optional的当前非空值的Optional
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
// 返回一个 Optional指定值的Optional,如果非空,则返回一个空的 Optional
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
// 如果Optional中有一个值,返回值,否则抛出 NoSuchElementException 。
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
// 返回true如果存在值,否则为 false
public boolean isPresent() {
return value != null;
}
// 如果存在值,则使用该值调用指定的消费者,否则不执行任何操作。
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
// 如果一个值存在,并且该值给定的谓词相匹配时,返回一个 Optional描述的值,否则返回一个空的 Optional
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
// 如果存在一个值,则应用提供的映射函数,如果结果不为空,则返回一个 Optional结果的 Optional 。
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
// 如果一个值存在,应用提供的 Optional映射函数给它,返回该结果,否则返回一个空的 Optional 。
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
// 如果值存在,就返回值,不存在就返回指定的其他值
public T orElse(T other) {
return value != null ? value : other;
}
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
}
关于of方法,现在好像很流行,就是提供一个static方法,方法名称叫of,方法的返回值返回当前类,并且把构造函数设置为私有private,用静态of方法来代替构造函数。
public class User {
private String username;
private Integer age;
private User() {
}
public static User of() {
return new User();
}
private User(String username, Integer age) {
this.username = username;
this.age = age;
}
public static User of(String username, Integer age) {
return new User(username, age);
}
}
public static void main(String[] args) {
// Optional类已经成为Java 8类库的一部分,在Guava中早就有了,可能Oracle是直接拿来使用了
// Optional用来解决空指针异常,使代码更加严谨,防止因为空指针NullPointerException对代码造成影响
String msg = "hello";
Optional<String> optional = Optional.of(msg);
// 判断是否有值,不为空
boolean present = optional.isPresent();
// 如果有值,则返回值,如果等于空则抛异常
String value = optional.get();
// 如果为空,返回else指定的值
String hi = optional.orElse("hi");
// 如果值不为空,就执行Lambda表达式
optional.ifPresent(opt -> System.out.println(opt));
}
版权声明
本文为[Mrchai521]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4490996/blog/4557614
边栏推荐
- 6.2 handleradapter adapter processor (in-depth analysis of SSM and project practice)
- Introduction to Google software testing
- Pollard's Rho algorithm
- GUI engine evaluation index
- Jmeter——ForEach Controller&Loop Controller
- 仅用六种字符来完成Hello World,你能做到吗?
- NLP model Bert: from introduction to mastery (2)
- With the advent of tensorflow 2.0, can pytoch still shake the status of big brother?
- How to use Python 2.7 after installing anaconda3?
- Music generation through deep neural network
猜你喜欢

What are PLC Analog input and digital input

NLP model Bert: from introduction to mastery (2)

GUI engine evaluation index

Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?
![[C / C + + 1] clion configuration and running C language](/img/5b/ba96ff4447b150f50560e5d47cb8d1.jpg)
[C / C + + 1] clion configuration and running C language

The difference between gbdt and XGB, and the mathematical derivation of gradient descent method and Newton method

文件过多时ls命令为什么会卡住?

Interface pressure test: installation, use and instruction of siege pressure test

A course on word embedding

vue-codemirror基本用法:实现搜索功能、代码折叠功能、获取编辑器值及时验证
随机推荐
Analysis of partial source codes of qthread
6.1.1 handlermapping mapping processor (1) (in-depth analysis of SSM and project practice)
Multi classification of unbalanced text using AWS sagemaker blazingtext
[actual combat of flutter] pubspec.yaml Configuration file details
ES6学习笔记(二):教你玩转类的继承和类的对象
[Xinge education] poor learning host computer series -- building step 7 Simulation Environment
Named entity recognition in natural language processing: tanford core LP ner (1)
How to use parameters in ES6
【字节跳动 秋招岗位开放啦】Ohayoo!放学别走,我想约你做游戏!!!
Python filtering sensitive word records
How to hide part of barcode text in barcode generation software
一路踩坑,被迫聊聊 C# 代码调试技巧和远程调试
It's easy to operate. ThreadLocal can also be used as a cache
Three Python tips for reading, creating and running multiple files
GUI engine evaluation index
Introduction to the structure of PDF417 bar code system
用一个例子理解JS函数的底层处理机制
Who says cat can't do link tracking? Stand up for me
一篇文章教会你使用HTML5 SVG 标签
Brief introduction of TF flags