It's been about two months since Java 11 was officially released. Java is changing in many ways, such as paying for the JDK, Now, let's go back to the basics and summarize Java 8. I will mainly describe the functions that are often used.
By the way, the author has only Java 7 experience up to the previous site, Java 8 history is about half a year.
--Lambda
Let's take a closer look.
It seems that it is also called a closure by another name. (I've never seen anyone call that) Let's see the actual description of what it looks like.
Sample.java
(x, y) -> {return x + y;}
/*
(Arguments of the method to implement) -> {processing}
*/
... That's why it feels like.
What is a lambda expression in the first place? ** A function that allows you to concisely describe the implementation of a functional interface as an expression **.
… And the unfamiliar word ** functional interface ** came up. Roughly speaking, think of it as an interface that implements only one abstract method [^ 1] **.
So to summarize it in a little more detail, ** A feature that allows you to concisely describe the implementation of an interface that has only one abstract method implemented **.
For example, let's implement the following functional interface.
Sample.java
@FunctionalInterface
public interface SampleInterface {
void sayHi();
}
Let's implement the interface normally.
SampleImpl1.java
public class SampleImple1 {
public void greeting() {
SampleInterface sample = new SampleInterface() { //Implement interface
void sayHi() {
System.out.println("Hi!"); //Describe the process you want to implement
}
}
sample.sayHi(); //Processing execution
}
}
I just want to say hello, but it's very unpleasant to have to bother to implement new processing. Let's use a lambda expression.
SampleImpl2.java
public class SampleImpl2 {
public void greeting(String name) {
SampleInterface sample = () -> System.out.println("Hi!"); //Implementation and processing description can be combined
sample.sayHi(): //Processing execution
}
}
Don't you think it's pretty clean? Being concise is ** friendly to the implementer, of course, but it also makes the code easier for the reader to understand because it eliminates the need for redundant writing. It also has a positive impact on the entire project.
I think it's easier to understand if you actually write the code than you see it in an article or read it in a book like this. If you haven't written it yet or haven't seen it in the field, please write it! !!
Optional Optional that is still indebted to me. I personally find it most convenient.
What the heck is it is a feature that indicates ** the object may be null **. The actual detailed functions (methods) will be left to Official Reference. In order to read the code introduced this time, I would like you to prepare only the following methods.
Let's take a look at the scene where you actually feel the description and umami.
Let's see a case where you want to make a DB reference and throw your own exception if you can't get anything.
First of all, if you did not use Optional.
OptionalService1.java
SampleEntity sampleEntity = sampleDao.selectById(id); //Execute DB reference
if (isNull(sampleEntity)) { //If the entity is null
throw new ApplicationException("errorCode", "Could not get value from DB"); //Throw an exception
}
It's a relatively simple category, but I hate having to write an if statement. In this example, you don't have to worry about nesting, With on-site code, the nesting is already quite deep, and even if branching may feel annoying.
Now let's use Optional.
OptionalService2.java
Optional<SampleEntity> sampleEntity = Optional.ofNullable(sampleDao.selectById(id))
.orElseThrow(() -> new ApplicationException("errorCode", "Could not get value from DB"));
… It ended in one line. It's been a little longer. .. And it comes out with a lambda expression. It comes out because it is convenient. it can not be helped.
Below is a brief explanation.
to get ʻOptional.empty ()
if the return value of sampleDao.selectById ()
is null, or ʻOptional throws an exception when the acquisition result is ʻOptional.empty ()
.So if no exception is thrown here, it is certain that sampleEntity
is not Optional.empty (). Easy to understand!
If you've removed the reference I introduced earlier, you'll know.
Other useful features such as map
and ʻor ElseGet` are provided. Let's use it!
As mentioned earlier, Optional expresses that it may be ** null **. The method is expressed by the method when wrapping with Optional or when fetching the value inside.
--Method to wrap in Optional --of… throw an exception if the wrapping object is null - ofNullable --Method to retrieve value from Optional --get ... Throw an exception if the Optional you are trying to retrieve is empty - orElseGet - orElseThrow
Therefore, ** do not use ofNullable for objects that can never be null (for example, columns that are NOT NULL in DB constraints), but use of **. This will allow anyone who sees the code later to understand that "this item is unlikely to be null" **. You don't have to write unnecessary tests.
After all, no matter how useful the function is provided, it will not be effective unless the user understands it. (Commandment)
Stream The name is cool. Stream is a function that allows you to write operations on arrays and Lists in a concise manner **. In addition, detailed functions have been handed over to Official Reference. I would like you to prepare for the following.
Let's assume that there is a process to output the names that can be collectively acquired from the DB in order.
I will try it with an extended for statement.
ForSample.java
for (SampleEntity entity : entityList) { //Get the contents of the List one by one
System.out.println(entity.getName());
}
I don't think there is much processing to output a person's name without thinking calmly. Because it is an example. The nest will be deeper again. I hate.
Let's use Stream.
StreamSample.java
entityList.stream.map(x -> x.getName()).forEach(System.out::println);
This also ended in one line. And it's short.
A brief explanation.
map ()
and return it to the stream. ** (Intermediate operation) **forEach ()
executes` System.out :: println'for each element of the stream. ** (Termination operation) **I think it's okay if you can roughly recognize that ** the intermediate operation processes the elements of the array and list, stores them in the stream, and the terminal operation executes them collectively for the stream **.
There are other methods that are too convenient, such as filter ()
, sorted ()
and distinct ()
.
Please try using that as well.
When I write it again, many things that can easily describe existing functions are added rather than new functions. I also thought that I was actually using it a lot.
Simple is the best for great people! I think that just reading and writing these will make you more like an engineer!
Until the end Thank you for reading! We look forward to your comments and suggestions! !!
[^ 1]: Strictly different. For more information, click here [https://qiita.com/lrf141/items/98ffbeaee42d30cca4dc#%E9%96%A2%E6%95%B0%E5%9E%8B%E3%82%A4%E3 % 83% B3% E3% 82% BF% E3% 83% BC% E3% 83% 95% E3% 82% A7% E3% 83% BC% E3% 82% B9% E3% 82% 92% E7% 90 Please see% 86% E8% A7% A3% E3% 81% 99% E3% 82% 8B).
Recommended Posts