In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to understand the development process from Java 8 to Java 15". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Functional programming (Java 8)
In Java 8, functional programming and lambda are added as language features. The two core examples of functional programming are immutable values and ways to promote functions to first-class citizens. The data goes through a series of modification steps, each of which requires some input and maps it to the new output. Functional programming can be used with Streams and null security monad in Java (optional), as shown below.
List stringList = Arrays.asList ("Hello", "World", "How", "Are", "You", "Today"); / / functional style stringList.stream () .filter (s-> s.equals ("Hello") | | s.equals ("Are")) .map (s-> s + "String") .forEach (System.out::println)
Stream (Java 8)
For general computer programs, it is usually necessary to use a list of values and perform a given conversion for each value. Before Java 8, you had to use a for loop to do this conversion, but from now on, you can use Streams in the following ways:
Stream.of ("hello", "great") .map (s-> s + "world") .forEach (System.out::println); > hello world > great world
The map function takes a lambda as input, which will be applied to all elements in the stream.
Streams can work on lists, collections, and maps (through transformation). Thanks to Streams, you can get rid of almost all the loops in your code!
Optional (Java 8)
Another common problem in Java is null pointer exceptions. Therefore, Java introduces Optional-a monad that wraps a reference that may or may not be null. Updates can be applied to this Optional in a functional manner:
Optional.of (new Random (). NextInt (10)) .filter (I-> I% 2 = = 0) .map (I-> "number is even:" + I) .ifPresent (System.out::println); > number is even: 6
In the above code snippet, we create a random number, wrap it in an Optional object, and then print only even numbers.
JShell (Java 9)
Finally, we have a REPL for Java. Its name is JShell! Instead, you can execute one command at a time and see the results immediately. This is a simple example:
$/ bin/jshell jshell > System.out.println ("hello world") hello world
People who are familiar with interpretive languages such as JavaScript or Python have long been satisfied with REPL, but so far this feature has been missing in Java. JShell allows you to define variables, but you can also define more complex entities, such as multiline functions, classes, and execution loops. In addition, JShell supports autocomplete, which can come in handy if you don't know the exact methods provided by a given Java class.
Factory method for immutable sets (Java 9)
For a long time, there was a lack of simple initialization of lists in Java, but now it's over. Previously, you had to do the following:
Jshell > List list = Arrays.asList (1,2,3,4) list = > [1,2,3,4]
Now simplify it as follows:
Jshell > List list = List.of (1,2,3,4) b = = > [1,2,3,4]
Lists, collections, and mappings exist such (...) Method. They all create an immutable object with a simple line of code.
Type inference using var (Java 10)
Java 10 introduces a new var keyword that allows the type of variable to be omitted.
Jshell > var x = new HashSet () x = > [] jshell > x.add ("apple") $1 = = > true
In the above code snippet, the compiler can infer the type of x as HashSet.
This feature helps reduce boilerplate code and improve readability. However, it has some limitations: you can only use var inside the method body, and the compiler infers types at compile time, so everything is still statically typed.
Single source file startup (Java 11)
Previously, when you write a simple Java program that contains a file, you must first compile the file using javac, and then run it using Java. In Java 11, you can complete two steps with one command.
First, define a single source file, Main.java:
Public class Main {public static void main (String [] args) {System.out.println ("hello world");}}
Now you can compile and run it in one step:
$java. / Main.java hello world
For a simple launcher or experiment that consists of only one Java class, this ability to start a single source file will make your life easier.
Switch expression (Java 12)
Java 12 brings us Switch expressions. A quick demonstration of how this expression differs from the old switch statement.
The old switch statement defines the flow of the program:
Jshell > var I = 3 jshell > String s; jshell > switch (I) {... > case 1: s = "one"; break;... > case 2: s = "two"; break;... > case 3: s = "three"; break;... > default: s = "unknown number";. >} jshell > s = = > "three"
Instead, the new switch expression returns a value:
Jshell > var I = 3; jshell > var x = switch (I) {... > case 1-> "one";... > case 2-> "two";... > case 3-> "three";... > default-> "unknown number";... >}; x = > "three"
To sum up, the old switch statement is used for program flow, and the new switch expression resolves to a value.
Note that this new switch statement is a mapping function: there is only one input (I in the above case) and only one output (x in this case). In fact, this is a pattern matching feature that helps make Java more compatible with functional programming principles. Similar switch statements have been in Scala for some time.
There are a few things to pay attention to:
Instead of double dots, we use arrows->
No need for Break
When considering all possible scenarios, you can omit the default
To enable this feature in Java 12, use-enable-preview-source 12
Multiline string (Java 13)
Have you ever defined a long multiline string, such as JSON or XML? By now, you may have compressed everything on one line and used the newline character n, but that makes String harder to read. Java 13 comes with a multiline string!
Example:
Public class Main {public static void main (String [] args) {var s = "" {"recipe": "watermelon smoothie", "duration": "10 mins", "items": ["watermelon", "lemon", "parsley"]} ""; System.out.println (s);}}
Now, let's start running the main method through a single file:
Java-enable-preview-source 13 Main.java {"recipe": "watermelon smoothie", "duration": "10 mins", "items": ["watermelon", "lemon", "parsley"]}
The resulting string spans multiple lines, the quotation marks "" remain intact, and even the tab t is preserved!
Data class: Record record (Java 14)
Of all the new features in this article, this is probably the one I'm most excited about: finally, there are data classes in Java! These classes are declared using the record keyword and have automatic Getter, constructors, equals () methods, and so on. In short, you can get rid of a lot of boilerplate code!
Jshell > record Employee (String name, int age, String department) {} | created record Employee jshell > var x = new Employee ("Anne", 25, "Legal"); x = = > Employee [name=Anne, age=25, department=Legal] jshell > x.name () $2 = > "Anne"
Scala has similar functionality for case classes and data classes for Kotlin. So far, many developers in Java have used Lombok, which provides a number of features that now inspire the documentation of Java 14. For more information, see the Baeldung article.
Instanceof without Cast (Java 14)
Earlier versions of Java already include the instanceof keyword:
Object obj = new String ("hello"); if (obj instanceof String) {System.out.println ("String length:" + ((String) obj) .length ());} view raw
Unfortunately: first, we check whether s is of type String, and then cast it again to get its length.
Now with Java 14, the compiler is smart enough to automatically infer types after instanceof checking:
Object obj = new String ("hello"); if (obj instanceof String mystr) {System.out.println ("String length:" + mystr.length ());}
Sealed classes (Java 15)
Using the sealed keyword, you can restrict which classes can extend a given class or interface. This is an example:
Public sealed interface Fruit permits Apple, Pear {String getName ();} public final class Apple implements Fruit {public String getName () {return "Apple";}} public final class Pear implements Fruit {public String getName () {return "Pear";}}
So how does this help us? Well, now you know how many kinds of fruits there are. In fact, this is an important step towards fully supported pattern matching, where you can treat classes like enumerations. This sealing function is well integrated with the new switch expression introduced earlier.
Bonus: license terms updated from Java 8
The last topic of this article: licensing. Most of you have heard that Oracle has stopped updating Java 8 (free commercial version). So this is your choice:
Use a newer version of Oracle JDK (Oracle provides free security updates within 6 months of each release)
Use the old version of JDK at your own risk
With older OpenJDK Java versions, those versions still get security updates from the open source community or third-party vendors.
Pay major support costs to Oracle (e.g. Java 8: support until 2030)
Below, you can view the provisional Oracle support period for each JDK:
> Oracle support timeline per JDK
Oracle's new licensing model is affected by the new release cycle: Oracle will release a new version of Java every six months. This new release cycle helps Oracle improve Java faster, get faster feedback through experimental features, and catch up with more modern languages such as Scala,Kotlin and Python.
This is the end of the content of "how to understand the Development from Java 8 to Java 15". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.