I tried to summarize Java 8 now

Introduction

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.

Frequently used added features

--Lambda

Let's take a closer look.

Lambda

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?

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 **.

When do you feel the taste of lambda style?

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.

A scene where you can feel the actual 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.

  1. Use ʻofNullable () to get ʻOptional.empty () if the return value of sampleDao.selectById () is null, or ʻOptional ` if you can get something. Will return it.
  2. ʻorElseThrow () 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!

important point

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.

A scene where you can feel the actual description and umami

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.

  1. Get the name from the Entity retrieved from the List with map () and return it to the stream. ** (Intermediate operation) **
  2. 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.

Finally

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

I tried to summarize Java 8 now
I tried to summarize Java learning (1)
I tried to summarize Java lambda expressions
I tried to summarize iOS 14 support
I tried to interact with Java
~ I tried to learn functional programming in Java now ~
I tried to summarize the basics of kotlin and java
I tried to summarize the methods used
I tried to summarize the Stream API
What is Docker? I tried to summarize
I tried to summarize the methods of Java String and StringBuilder
I tried to summarize about JVM / garbage collection
I tried to make Basic authentication with Java
java I tried to break a simple block
I tried to implement deep learning in Java
[Must see !!!] I tried to summarize object orientation!
I tried to output multiplication table in Java
I tried to break a block with java (1)
[Introduction to Java] I tried to summarize the knowledge that I think is essential
I tried Drools (Java, InputStream)
I tried using Java REPL
Java8 to start now ~ Optional ~
I tried metaprogramming in Java
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
I tried to summarize the state transition of docker
[Java] I tried to solve Paiza's B rank problem
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to summarize various link_to used this time
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
I tried to find out what changed in Java 9
I tried using anakia + Jing now
I tried to create a java8 development environment with Chocolatey
I tried to chew C # (indexer)
I tried to modernize a Java EE application with OpenShift.
[JDBC] I tried to access the SQLite3 database from Java.
I tried UDP communication with Java
I tried to explain the method
I want to use the Java 8 DateTime API slowly (now)
I tried to make Java Optional and guard clause coexist
I tried the Java framework "Quarkus"
I tried to summarize the basic grammar of Ruby briefly
I tried using Java8 Stream API
I tried to summarize personally useful apps and development tools (development tools)
I tried to convert a string to a LocalDate type in Java
I tried using JWT in Java
I tried using Dapr in Java to facilitate microservice development
I tried to understand nil guard
I tried to make a client of RESAS-API in Java
Java 8 ~ Stream API ~ to start now
I tried to chew C # (polymorphism: polymorphism)
I tried to summarize object orientation in my own way.
I tried using Java memo LocalDate
I tried to explain Active Hash
I tried using GoogleHttpClient of Java