Java 8 new features learning

Rash 2020-11-07 20:37:34
java new features learning


1、 Default method in interface

Java8 The interface is allowed to contain methods with specific implementation , This method is called “ The default method ”, Use default Keyword modification .
Such as :

public interface MyInterface {
String notDefault();
default String testDefault() {
return "Hello Default Method";
}
}12345678

The implementation class of this interface only needs to implement abstract methods , The default method can be used directly .

MyInterface myInterface = new MyInterface() {
@Override
public String notDefault() {
return " This is not a default Method , The implementation class needs to override this method ";
}
};
System.out.println(myInterface.notDefault());
System.out.println(myInterface.testDefault());123456789

Interface of the default method “ Class first ” principle :

If an interface defines a default method , When a method with the same name is defined in another parent class or interface

  • Choose the method in the parent class . If a specific implementation is provided in a parent class , Default methods with the same name and parameters in the interface are ignored . Test code :
public class MySuperClazz {
public String testDefault() {
return "This is default method";
}
}
public interface MyInterface {
default String testDefault() {
return "Hello Default Method";
}
}
public class MyClazz extends MySuperClazz implements MyInterface{
}
MyClazz myClazz = new MyClazz();
System.out.println(myClazz.testDefault());12345678910111213141516171819

Output results :

This is default method1
  • Interface conflict , If a parent interface provides a default method , Another interface also provides a method with the same name and parameter list ( Whether the method is the default method or not ), Then the implementation class must override this method to resolve the conflict .

Test code :

public class MyClazz /*extends MySuperClazz */implements MyInterface,MyInterface2{
@Override
public String testDefault() {
return " Test methods with the same name in two interfaces ";
}
}
public interface MyInterface2 {
default String testDefault() {
return "Hello Default Method2";
}
}
public interface MyInterface {
default String testDefault() {
return "Hello Default Method";
}
}123456789101112131415161718192021

test result :

 Test methods with the same name in two interfaces 1

Java8 Static methods can also be declared in the interface of

public interface MyInterface {
static void testStatic() {
System.out.println(" Static methods ");
}
}123456

2、Lambda expression

The code mentioned above

MyInterface myInterface = new MyInterface() {
@Override
public String notDefault() {
return " This is not a default Method , The implementation class needs to override this method ";
}
};123456

Can pass Lambda The expression is rewritten as follows

MyInterface myInterface = () -> " This is not a default Method , The implementation class needs to override this method ";1

This form , That is java8 A more concise way to provide , namely Lambda expression . Compared with jdk1.7 Previous code , Use Lambda The expression is shorter and easier to read .

Lambda Expression is a kind of “ Grammatical sugar ”, Need functional interface support .
Lambda The data type of the argument list of an expression can be omitted without writing , because JVM The compiler can infer data types from context , namely : Type inference .Java The compiler can automatically identify the type of parameters , So you can omit the type .

Lambda The expression can be divided into two parts :
left : It specifies Lambda All the parameters required by the expression
On the right side : It specifies Lambda body , namely lambda The function that the expression is to perform

Lambda Expressions have the following formats :

  • Syntax format 1 : No parameter , No return value
 Format :
() -> System.out.println("Hello Lambda");
example :
Runnable r1 = () -> System.out.println("Hello Lambda");1234
  • Syntax 2 : There is a parameter , And no return value
 Format :
(x) -> System.out.println(x)
There is only one parameter, and the bracket can be left blank
x -> System.out.println(x)
example :
Consumer<String> con = (x) -> System.out.println(x);
Consumer<String> con2 = x -> System.out.println(x);
con.accept("zhw");
con2.accept("nb");123456789
  • Syntax 3 : There are more than two parameters , also lambda There are multiple statements in the body , And there is a return value , If more than one statement must be used {}
 example :
Comparator<Integer> com = (x,y) -> {
System.out.println(" Syntax 3 ");
return Integer.compare(x,y);
};12345
  • Syntax format 4 :lambda Weight has only one sentence , And it has a return value , Braces can be omitted ,return It can be omitted
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);1

Lambda The range of expressions :

about lambdab Variables outside the expression , The granularity of access is very similar to that of anonymous objects .
You can access the local part of the corresponding external region final Variable , And member variables and static variables .
Be careful :final Keywords can be omitted , But it's still implicitly interpreted as final Variable to handle .

Method reference :

if Lambda The content in body has methods that are already implemented , We can use “ Method reference ”,( It can be understood that the method reference is Lambda Another form of expression )

Be careful :
1、 Lambda The parameter list and return value types of the calling method in body , It should be consistent with the parameter list and return value type of abstract method in functional interface
2、 if lambda The first parameter in the argument list is The caller of the instance method , And the second argument is the argument to the instance method , have access to ClassName::method In the form of

Three syntax formats of method references :

  • object :: Instance method name
  • class :: Static method name
  • class :: Instance method name

Constructor reference

Format :

  • ClassName::new

Be careful :
The parameter list of the constructor to be called should be consistent with that of the abstract method in the functional interface

3、 Functional interface

As mentioned above Lambda Expressions need the support of functional interface, so what is functional interface ? A functional interface is one that must have and only one abstract method declaration ,Lambda The expression must match the declaration of the abstract method , Because the default method is not abstract , So you can add any default method in the functional interface .

When defining a functional interface, you can use @FunctionalInterface annotation , The compiler will determine whether the defined interface satisfies the condition that a function is an interface , If not satisfied , The compiler throws an exception .

@FunctionalInterface
public interface MyFunction<T,R> {
R get(T t1,T t2);
}12345

Java8 Built-in functional interface :

Consumers

Consumer<T> : Consumer interface ,Consumer Represents the operation to be performed on an input parameter .
void accept(T t);
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));12345

Suppliers

Supplier<T> : Supply type interface , The mouth produces a result of a given type . And Function The difference is ,Supplier No input parameters .
Supplier<Person> personSupplier = Person::new;
personSupplier.get(); // new Person1234

Functions

Function<T,R> : Functional interface , Take a parameter (T), And return a single result (R). The default method can string multiple functions together (compse, andThen).
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123"); // "123"12345

Predicates

Predicate<T> : Paragraph type interface , It's a Boolean function , The function has only one parameter .Predicate Interface contains a variety of default methods , Used to deal with complex logical verbs (and, or,negate)
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo"); // true
predicate.negate().test("foo"); // false
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();123456789

4、Stream Data flow

A data stream represents a sequence of elements , And support different kinds of operations to perform the calculation on the element . Data streams are monomers (Monad), And in Java8 It plays an important role in functional programming .

flow (Stream) What is it : It's the data channel , Used to manipulate data sources ( aggregate , Array etc. ) The generated sequence of elements “ Collections are about data , Flow is about computation ”.

Be careful :

  1. Stream You don't store elements by yourself
  2. Stream The source object does not change . contrary , They will return a new one that holds the results Stream
  3. Stream The operation is delayed . This means that they will wait until the results are needed .

Stream Three steps of operation :

  • Create data flow
  • Linking operations
  • Termination operation

Stream Operation process diagram of data flow :
 Picture description here

Data flow operations are either bridging operations ( The creation process can also be seen as a bridging operation ), Either terminate the operation , Data flow operations are mostly stateless and non intrusive , That is, when a function does not modify the underlying data source of the data stream , It's just undisturbed ; When the operation of a function does not depend on variable variables or states in any operation process in the external scope , It's stateless .

Create data flow :

establish Stream In five ways :
1、 Can pass Collection In the series collection stream() perhaps parallelStream() Method to get a serial stream or a parallel stream .

List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();12

2、 adopt Arrays Static methods in stream() Method to get the array stream

 Arrays.asList("a1", "a2", "a3").stream();1

3、 adopt Stream Static methods in a class of() Method get stream , You can create a data stream from a series of object references

Stream<String> stream = Stream.of(“aa”,”bb”,”cc”);1

4、 Create an infinite flow

// iteration
Stream<Integer> stream = Stream.iterate(0,(x) -> x+ 2);
Stream.limit(10).forEach(System.out::println)
// Generate
Stream.generate(()->Math.random()).forEach(System.out::println);12345

5、java8 Provides some special kinds of streams , Used to process basic data types int,long,double. Respectively IntStream,LongStream,DoubleStream

The data streams created in the first four ways are called “ Object data flow ”, The fifth way to create a flow is called “ Basic data flow ”, Basic data flow and object data flow are similar in usage , But there are some differences , The basic data stream uses special lambda expression , Such as :IntFunction instead of Function,IntPredicate instead of Predicate. At the same time, the basic data stream also supports some additional aggregation termination operations sum() and average() etc. . Sometimes it is necessary to convert the object data stream and the basic data stream . The conversion method is as follows :

Convert object data stream to basic data stream :

mapToInt() 、 mapToLong() and mapToDouble()
example :
Stream.of("a1", "a2", "a3")
.map(s -> s.substring(1))
.mapToInt(Integer::parseInt)
.max()
.ifPresent(System.out::println); 12345678

Stream data into basic data objects :

mapToObj()
example :
IntStream.range(1, 4)
.mapToObj(i -> "a" + i)
.forEach(System.out::println);123456

Linking operations :

Multiple join operations can be connected to form An assembly line , Unless the pipeline starts to terminate the operation , Otherwise, the join operation does not perform any processing , And in the termination operation, it's all done at once , be called “ Lazy evaluation ” or “ Delay the ”, Delay is an important feature of cohesion .

 example :
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> {
System.out.println("filter: " + s);
return true;
});123456

This code doesn't print anything to the console , Because the operation is not terminated , The join operation is only executed when the operation call is terminated .

There are mainly several ways to link up :

Screening and slicing

filter— receive Lambda, Exclude certain elements from six
limit— Truncation stream , Keep its elements to a given number
skip(n)— Skip the element , Back to a throw away before n A stream of elements . If there are not enough elements in the stream n individual , It returns an empty stream . And limit complementary
distinct— Screening , Of the elements generated by the flow hashCode() and equals() Remove duplicate elements
Internal iteration : There are iterations Stream API complete
External iteration : Write your own iteration operations 1234567

mapping

map— receive Lambda, Convert elements to other forms or extract information . Receive a function operation parameter , This function is applied to each element , And map it to a new element .
flatMap— Receive a function as an argument , Replace each value in the stream with another stream , Then link all the streams into one stream 123

Sort

sorted()— Natural ordering
sorted(Comparator com)— Custom sort 12

Termination operation :

In the data stream , Only when the termination operation is performed , The linking operation will be carried out at one time . There are several ways to terminate the operation :

Find and match

allMatch— Check to see if all elements match
anyMatch— Check that at least one element matches
noneMatch— Check that all elements are not matched
findFirst— Returns the first element in the current stream
findAny— Returns any element of the element in the stream
count— Returns the total number of elements in the stream
max— Returns the maximum value in the stream
min— Returns the minimum value in the stream 12345678

reduction

ruduce(T identity,BinaryOperator) / ruduce(BinaryOperator) – You can combine elements of the stream over and over again , Combine it into a single result .1

collect

collect— Convert streams to other forms . Receive one Collector Interface implementation , For giving Stream The method of summarizing elements in , Store the elements in the stream in different types of results .Java8 Through the built-in Collectors Class supports a variety of built-in collectors .
List<Person> filtered = persons.stream()
.filter(p -> p.name.startsWith("P"))
.collect(Collectors.toList());
System.out.println(filtered); // [Peter, Pamela]123456

5、 Parallel stream and serial stream

Serial stream : Execute a content on a thread

Arrays.asList("a1", "a2", "a3")
.stream()
.findFirst()
.ifPresent(System.out::println);1234

Parallel flow : Is to divide a content into multiple data fast , And use different threads to process the flow of each data block . Parallel flows can perform operations on multiple threads . It is mainly to solve the performance problem when dealing with a large number of elements .

Arrays.asList("a1", "a2", "a3")
.stream()
.findFirst()
.parallel()
.ifPresent(System.out::println);
--------------------------------------------------------------------
Arrays.asList("a1", "a2", "a3")
.parallelStream()
.findFirst()
.ifPresent(System.out::println);12345678910

Stream API Can be declaratively passed parallel() And sequential() Switching between parallel and serial streams .
Use... In a serial stream parallel() Switch to parallel stream , Use... In a parallel stream sequential() Switch to serial stream .

Java8 Better support for parallel streaming
Parallel streams use common ForkJoinPool , from ForkJoinPool.commonPool() Method provides . The maximum size of the underlying thread pool is five threads – Depending on CPU The number of physical cores of .

Fork/Join frame : If necessary , Talk about a big task , To break up (fork) Into a number of small tasks ( When split to inseparable ), And then the results of a small person operation are summarized (join).
 Picture description here

use “ Job theft ” Algorithm (work-stealing),Java8 This framework was not used much before , The main reason is that this method is too cumbersome to implement , and Java8 Make the implementation method very simple .

“ Job theft ” Algorithm : Algorithm refers to a thread stealing tasks from other queues to execute

For a common large task , We can cut this big task into many smaller ones , Then these little tasks are put in different queues , Each queue has a corresponding work execution thread to execute , When a thread needs to execute in the queue , After the task is completed , This thread will be idle , In order to improve thread utilization , These idle threads can steal tasks from other task queues , To avoid wasting your resources , This kind of idle in their own thread , At the same time steal other task queue task execution algorithm , It's job theft algorithms

6、Optional class

Optional Class is a container class , Represents the existence or non existence of a value , Can avoid null pointer exception .Optional It's not a functional interface , It's a sophisticated tool interface , In a way that NullPointException abnormal .Optional It's a simple value container , This value could be zero null, It can also be non-null, In order not to return directly null, We are Java 8 You're going to return a Optional class , Use Optional Class can avoid using if Conduct null Check , This process of checking is handled automatically by the underlying layer . The main methods are as follows :

of(T t) : Create a Optional example
empty() : Create an empty Optional example
ofNullable(T t) : if t Not for null, establish Optional example , Otherwise, create an empty Optional example
isPresent() : Determine if the value... Is included
orElse(T t) : If the calling object contains values , Returns the value , Otherwise return to t
orElseGet(Suppplier s) : If the calling object contains values , Returns the value , Otherwise return to s Get the value of
map(Function f) : If it's worth handling , And return the processed Optional, Otherwise return to Optional.empty()
flatMap(Function mapper) : And map similar , The return value is required to be Optional12345678

7、JAVA8 New time pack

Java 8 Including a new time and date API, These functions are all placed in java.time It's a bag . The main methods are as follows :

LocalDate,LocalTime,LocalDateTime : Time
Instant : Time stamp ( With Unix First year :1970 year 1 On January 1st 00:00:00 The value of milliseconds to a certain time )
Duration : Calculate two “ Time ” Spacing between
Period : Calculate two “ date ” Spacing between
TemporalAdjust : Time corrector
DateTimeFormatter : Format time / date
ZonedDate,ZonedTime,ZonedDateTime : The time zone
版权声明
本文为[Rash]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云