Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of New Features of JDK8

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this "case analysis of JDK8 new features" article, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "JDK8 new feature case analysis" article.

Functional programming

Object-oriented emphasizes that "everything is an object". If you want to do something, you must find an object to do. Functional programming emphasizes "what to do" rather than "how to do it".

Ordinary open thread

/ / Anonymous inner class object

Runnabletask=newRunnable () {

@ Override

Publicvoidrun () {

System.out.println ("Crows fly")

}

}

NewThread (task) .start ()

More free video tutorials related to java: java online tutorials

Functional programming starts threads

NewThread (()-> System.out.println ("Tornado destroys parking lot"). Start ()

The front parentheses: method parameters, write () when there are no parameters, the arrow points to what you want to do, and behind the arrow is like the method body curly braces, representing the specific content to be done.

Lambda expression

Lambda expressions, also known as closures, are the most important new feature that drives the release of Java8.

Lambda allows you to use a function as an argument to a method (the function is passed into the method as an argument). Using Lambda expressions can make your code more concise and compact.

Three elements: parameter, arrowhead, code

Format: (parameter type parameter name)-> {some code}

Prerequisite for using Lambda expressions: there must be an interface and there is only one and only one abstract method in the interface

Demo: write a Cook interface with a makeFood () method in it

Publicstaticvoidmain (String [] args) {

Method (()-> {

System.out.println ("flash knife start!")

})

}

Privatestaticvoidmethod (Cookcook) {

Cook.makeFood ()

}

Lambda expression omits the rule:

Parameter types can be omitted. But you can only omit the types of all parameters at the same time, or not at all. If there is only one parameter, then parentheses can be omitted. If there is only one statement in curly braces, then return, braces and semicolons can be omitted regardless of whether there is a return value or not.

Publicstaticvoidmain (String [] args) {

Method ((aforme b)-> aforb)

}

Privatestaticvoidmethod (Calculatorcalculator) {

Intresult=calculator.sum (1234. 9876)

System.out.println (result)

}

When you new an interface, you can also use lambda expressions instead of anonymous inner classes

Runnabletask= ()-> System.out.println ("flash knife start!")

NewThread (task) .start ()

Functional interface

There is one and only one abstract method in the interface, called a functional interface.

The annotation @ FunctionalInterface has been added to JDK8 to check whether an interface is a functional interface. If it is not a functional interface, an error will be reported at compile time. The @ FunctionalInerface annotation is optional, and even without it, it is still a functional interface as long as the interface meets the definition requirements of a functional interface.

@ FunctionalInterface

PublicinterfaceMyInterface {

Voidmethod ()

}

Method reference

Printerprinter= (str)-> System.out.println (str); this code can actually be abbreviated.

As long as it is deducable, it can be referenced, so passing parameters does not make sense, so here you can use method references to abbreviate System.out::println.

Starting with java8, a new operator is introduced, the method reference character (two colons are written in succession), the expression is a method reference, the method reference and Lambda are essentially the same, and the purpose is to simplify the writing of Lambda expressions.

Lambda is written as: s-> System.out.println (s)

Method reference: System.out::println

The two kinds of writing are completely equivalent.

Publicstaticvoidmain (String [] args) {

Method (System.out::println)

}

Privatestaticvoidmethod (Printerprinter) {

Printer.print ("hello")

}

Interface

Default method

The interface is supposed to be two abstract methods, but now it needs to be changed into three abstract methods, and its implementation class also needs to implement new methods.

When there are too many implementation classes, it is troublesome to operate. JDK used to use the open-closed design pattern: open to extensions and closed to modifications. That is, create a new interface, inherit the original interface, and define the new method, but in this case, the original implementation class does not have a new method, so you can use the interface default method.

Keyword is modified with default, and the method requires the body of the method. All subclasses of this method will be implemented by default (you don't have to write it yourself). If you want to overwrite it, you can also overwrite it in the implementation class.

/ * *

* starting with java8, the default method of default can be defined in the API.

* modifier: publicdefault (public can be omitted, default cannot be omitted)

* /

PublicinterfaceMyInterface {

Voidmethod1 ()

Voidmethod2 ()

DefaultvoidmethodNew () {

System.out.println ("Interface default method execution")

}

}

Note: the default method in the interface is equivalent to a new keyword, and the "default" of the four modifiers is not the same concept.

The active use of the default keyword can make the program achieve the effect of "multi-inheritance".

Static method

Starting with java8, static methods are allowed to be defined in the interface, using the same as static methods in general classes.

PublicinterfaceAnimal {

Voideat ()

StaticAnimalgetAnimal () {

ReturnnewCat ()

}

}

Streaming operation

The first feeling of streaming to developers is to make collection operations much simpler. Operations that usually require multiple lines of code can be implemented in one line with streaming.

For example, if we want to filter out all even numbers from a collection of integers and encapsulate them into a new List return, we need to do this with the following code before java8:

For a collection of nums:

Listevens=newArrayList ()

For (finalIntegernum:nums) {

If (num%2==0) {

Evens.add (num)

}

}

With java8 streaming, we can simplify the code to:

Listevens=nums.stream () .filter (num- > num%2==0) .conversation (Collectors.toList ())

First of all, let's briefly explain the meaning of the above line. The stream () operation converts the collection into a flow, and filter () performs our custom filtering processing, here we filter out all the even numbers through the lambda expression, and finally we encapsulate the result through collect () and specify it to be encapsulated as a List collection return through Collectors.toList ().

Common operation cases:

/ / initialize the list collection

Listlist=newArrayList ()

List.add ("Test data 1")

List.add ("Test data 2")

List.add ("Test data 3")

List.add ("Test data 12")

/ / use lambda expression to traverse the collection

List.forEach (s-> System.out.println (s))

/ / filter elements by combining Predicate use and filter criteria

Predicatecontain1=n- > n.contains ("1")

Predicatecontain2=n- > n.contains ("2")

/ / traverse the collection according to the condition

List.stream () .filter (contain1) .forEach (n-> System.out.println (n))

List.stream () .filter (s-> contain1.test (s)) .forEach (s-> System.out.println (s))

List.stream () .filter (contain1.and (contain2)) .forEach (n-> System.out.println (n))

List.stream () .filter (contain1.or (contain2)) .forEach (n-> System.out.println (n))

/ / put the filtered elements back into a collection

ListnewList=list.stream () .filter (contain1.and (contain2)) .conversation (Collectors.toList ())

Decimal summation in a set

BigDecimalsum=list

.stream ()

.map (Person::getAmount)

.reduce (BigDecimal::add)

.get ()

/ / sort, also need a new collection to receive

ListresultList=newArrayList ()

ResultList=list.stream () .sorted (Comparator.comparing (Student::getAge)) .conversation (Collectors.toList ())

The above is about the content of this article on "case Analysis of JDK8 New Features". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report