当前位置:网站首页>What grammar is it? ]
What grammar is it? ]
2020-11-06 21:19:00 【Mrchai521】
One : concise
There are three types of method references , Method references are made through a pair of double colons :: To express , Method reference is another way to write a functional interface
-
Static method reference , By class name :: Static method name , Such as Integer::parseInt
-
Instance method reference , By instance object :: Example method , Such as str::substring
-
Construction method reference , By class name ::new, Such as User::new
Two : Method reference
public final class Integer {
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
}
Quote... By method , You can assign a reference to a method to a variable , By assigning a value to Function, Explain that method reference is also a way of writing functional interface ,Lambda Expressions are also functional interfaces ,Lambda Expression is usually used to provide its own method body , The method reference usually refers to the ready-made method directly .
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) {
// Use double colons :: To construct static function references
Function<String, Integer> fun = Integer::parseInt;
Integer value = fun.apply("123");
System.out.println(value);
// Use double colons :: To construct non static function references
String content = "Hello JDK8";
Function<Integer, String> func = content::substring;
String result = func.apply(1);
System.out.println(result);
// Constructor reference
BiFunction<String, Integer, User> biFunction = User::new;
User user = biFunction.apply("mengday", 28);
System.out.println(user.toString());
// Function reference is also a functional interface , So you can also take a function reference as a parameter of a method
sayHello(String::toUpperCase, "hello");
}
// Method has two parameters , One is
private static void sayHello(Function<String, String> func, String parameter){
String result = func.apply(parameter);
System.out.println(result);
}
3、 ... and :Optional Optional value
stay Google Guava in Optional, stay Swift There are similar grammars in languages , stay Swift Take an optional value as a data type , The status is equal to the basic type , The status is very high .
/** * @since 1.8 */
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>();
private final T value;
private Optional() {
this.value = null;
}
// Returns an empty Optional example
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);
}
// Returns a Optional The current non null value of Optional
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
// Return to one Optional Specified value Optional, If it is not empty , Then return an empty Optional
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
// If Optional There is a value in , Return value , Otherwise throw NoSuchElementException .
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
// return true If there is value , Otherwise false
public boolean isPresent() {
return value != null;
}
// If there is value , Then use this value to call the specified consumer , Otherwise, nothing will be done .
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
// If a value exists , And the predicate given by the value matches , Return to one Optional The value described , Otherwise, return an empty Optional
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
// If there is a value , Then the mapping function provided by , If the result is not empty , Returns a Optional The results of 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));
}
}
// If a value exists , The application provides Optional The mapping function gives it , Return the result , Otherwise, return an empty 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));
}
}
// If the value exists , Just return the value , If it doesn't exist, it will return other specified values
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();
}
}
}
About of Method , It seems to be very popular now , Is to provide a static Method , The name of the method is of, Method returns the current class , And set the constructor to private private, Using static of Method instead of the constructor .
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 Class has become Java 8 Part of the class library , stay Guava There has been , Probably Oracle It's used directly
// Optional Used to solve null pointer exception , Make the code more rigorous , Prevent because of null pointer NullPointerException Impact on code
String msg = "hello";
Optional<String> optional = Optional.of(msg);
// Judge whether there is value , Not empty
boolean present = optional.isPresent();
// If it's worth it , Return value , If it is equal to empty, then throw the exception
String value = optional.get();
// If it is empty , return else The specified value
String hi = optional.orElse("hi");
// If the value is not null , Is executed Lambda expression
optional.ifPresent(opt -> System.out.println(opt));
}
版权声明
本文为[Mrchai521]所创,转载请带上原文链接,感谢
边栏推荐
- Ronglian completed US $125 million f round financing
- 意派Epub360丨你想要的H5模板都在这里,电子书、大转盘、红包雨、问卷调查……
- What is the tensor in tensorflow?
- Behind the record breaking Q2 revenue of Alibaba cloud, the cloud opening mode is reshaping
- 上海巨微专用蓝牙广播芯片
- How to turn data into assets? Attracting data scientists
- Summary of front-end performance optimization that every front-end engineer should understand:
- C# 调用SendMessage刷新任务栏图标(强制结束时图标未消失)
- CCR coin frying robot: the boss of bitcoin digital currency, what you have to know
- Event monitoring problem
猜你喜欢
Zero basis to build a web search engine of its own
Ronglian completed US $125 million f round financing
How much disk space does a new empty file take?
Share with Lianyun: is IPFs / filecoin worth investing in?
Use modelarts quickly, zero base white can also play AI!
git远程库回退指定版本
list转换map(根据key来拆分list,相同key的value为一个list)
嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:曾文旌
mongo 用户权限 登录指令
Staying up late summarizes the key points of report automation, data visualization and mining, which is different from what you think
随机推荐
意派Epub360丨你想要的H5模板都在这里,电子书、大转盘、红包雨、问卷调查……
Isn't data product just a report? absolutely wrong! There are university questions in this category
What is alicloud's experience of sweeping goods for 100 yuan?
Those who have worked in China for six years and a million annual salary want to share these four points with you
Zero basis to build a web search engine of its own
Tron smart wallet PHP development kit [zero TRX collection]
How to prepare for the system design interview
What kind of music do you need to make for a complete game?
Zero basis to build a web search engine of its own
细数软件工程----各阶段必不可少的那些图
An article will introduce you to CSS3 background knowledge
谷歌浏览器实现视频播放加速功能
How to turn data into assets? Attracting data scientists
2020-09-04:函数调用约定了解么?
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
Use modelarts quickly, zero base white can also play AI!
mongo 用户权限 登录指令
Elasticsearch Part 6: aggregate statistical query
File download manager realized by electron
Basic usage of Vue codemirror: search function, code folding function, get editor value and verify in time