About Lambda, Stream, LocalDate of Java8


Master how to use Lambda, Stream, and LocalDate so that you can use it on a regular basis!


What is Lambda?

Lambda is a way to define and use a method as a variable. Lambda allows you to write fewer lines of code. You can also pass the defined method as an argument to another method. Write methods in Lambda that are used only a few times and are not referenced by other classes!

Basic writing

Since Lambda is written by omitting all the function names to be overridden, it is necessary to inherit the interface in which only one method is defined. Java already provides functional interfaces that can be used according to the number of arguments and return values, so I will use them.

** * Caution: When using primitive types such as int and double for arguments and return values, use the corresponding interfaces! (Because there is a difference in performance) ** Example) // When you want to send an int and receive an int Function → IntUnaryOperator

The detailed types of interfaces are listed below. http://www.ne.jp/asahi/hishidama/home/tech/java/functionalinterface.html#h_Function

There is an argument return value, Function

It is defined as the argument type and the return type. Execution uses the ʻapply () method. There is also a BiFunction that can accept two arguments. If you want to specify int type for argument and return value, use ʻIntUnaryOperator instead of Function. The execution method is ʻapplyAsInt ()`.

import java.util.function.*;

//In main
Function<String, String> f = (i) -> { return i +"OK"; };
System.out.println(f.apply("test"));  // testOK

There are only arguments, Consumer

Specifies the argument type. Execution uses the ʻaccept () method. If you want to specify the argument as int type, use ʻIntConsumer.

import java.util.function.*;

//In main
Consumer<String> c = i -> { System.out.println(i); };
c.accept("testOK");  // testOK

There is only a return value, Supplier

Specifies the return type. Execution uses the get () method. If you want to specify the return value as int type, use ʻIntSupplier. The execution method is getAsInt ()`.

import java.util.function.*;

//In main
Supplier<String> s = () -> { return "testOK"; };
System.out.println(s.get());  // testOK

Predicate that takes an argument and returns a boolean value

Execution uses the test () method. The difference between Boolean specification of Function and Predicate is that Function returns Boolean, while Predicate returns boolean which is a primitive type. If you want to specify the argument as int type, use ʻIntPredicate`.

import java.util.function.*;

//In main
Predicate<String> p = (i) -> { return i.equals("AAA"); };
System.out.println(p.test("AAA"));  // true


What is Stream?

You can concisely write a List type for statement. You can also use Lambda as a method argument. When using it, import java.util.stream.

First, consider a normal for statement.

for(int i; i < 10; i++){
    System.out.println(i+"This is the second time");

If you write this in Stream

IntStream.range(0, 10).forEach(i -> System.out.println(i+"This is the second time"));

It will be simple.

Also, if you want to turn for for the elements of ArrayList,

//For the variable list
list.stream().forEach(i -> [processing])

You can write like this.

Intermediate operation and termination operation

The stream has an intermediate operation method that converts each element and a terminal operation method that finally returns and stores the value. Please note that the converted elements will not be saved unless the termination operation is performed.

The intermediate operations are as follows. .skip (n) ... Discard the first n elements. .limit (n) ... Extract only the first n items. .filter (i-> [condition]) ... Extract the one that meets the condition. .distinct () ... Remove duplicates. .sorted () ... Sort in natural order. It is also possible to specify a sort rule in parentheses. .map (i-> [Processing]) ... Process all elements.

The termination operations are as follows. .forEach (i-> [Processing]) ... Output. .findFirst () ... Returns the first element. .collect () ... Create the result. (Processing changes depending on the argument.) .count () ... Returns the number of elements. .allMach ([condition]) .anyMach ([condition]) .noneMach ([condition]) ... Determine if there is a match.


What is Local Date?

A class that processes dates. It's easier to handle than the Calendar class I've been using. Import and use java.time.LocalDate.

I will raise the operations that are often used below.

Get current date

LocalDate date = LocalDate.now();

Date set

Set 2020-01-01 localDate date = LocalDate.of(2020, 1, 1); Unlike Calendar, you don't have to set Month to -1!

String to date set

Import java.time.format.DateTimeFormatter.

date = LocalDate.parse("20200101",DateTimeFormater.ofPattern("yyyyMMdd")); Also possible below date = LocalDate.parse("2020-01-01");

Get date

Year date.getYear(); Month date.getMonth(); Day date.getDayOfMonth(); Day of the week date.getDayOfWeek();

Addition and subtraction

+10 days date.plusDays(10); -The 10th date.miusDays(10); +2 years date.plusYears(2);

Difference between dates

Import java.time.temporal.ChronoUnit.

Date difference long diff = ChronoUnit.DAYS.between(date1, date2);

Reference material

Lambda http://www.ne.jp/asahi/hishidama/home/tech/java/functionalinterface.html#h_Function https://qiita.com/sano1202/items/64593e8e981e8d6439d3

Stream http://www.ne.jp/asahi/hishidama/home/tech/java/stream.html https://qiita.com/kumazo/items/0876c5b251ecc131c960 https://qiita.com/kumazo/items/104fa685da8705b8cfd8 https://qiita.com/kumazo/items/284098c530fceb05805c

LocalDate https://blog.y-yuki.net/entry/2016/09/15/003000) https://m-shige1979.hatenablog.com/entry/2017/03/10/080000

Recommended Posts

About Lambda, Stream, LocalDate of Java8
About Java lambda expressions
About an instance of java
[Java11] Stream Summary -Advantages of Stream-
Java8 stream, lambda expression summary
Use Java lambda expressions outside of the Stream API
[Introduction to Java] About lambda expressions
About fastqc of Biocontainers and Java
[Introduction to Java] About Stream API
Java8 Lambda Expression & Stream Design Pattern Rethinking --Chain of Responsibility Pattern -
Basic processing flow of java Stream
The origin of Java lambda expressions
Nowadays Java lambda expressions and Stream API
[Java beginner] About initialization of multidimensional array
[Basic knowledge of Java] About type conversion
About Java interface
[Java] About arrays
Try Java 8 Stream
Java Stream API
Something about java
Where about java
About Java features
About Java threads
[Java] About interface
About Java class
About Java arrays
Hello Java Lambda
[Java] Lambda expression
Studying Java 8 (Stream)
About java inheritance
About interface, java interface
[Java] Overview of Java
Java Stream termination
Java lambda expression
[Java] Stream processing
About List [Java]
About java var
About Java literals
Java 9 Optional :: stream
About Java commands
About the description order of Java system properties
About the idea of anonymous classes in Java
[Java] Summary of how to abbreviate lambda expressions
[For beginners] About lambda expressions and Stream API
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -
About Java log output
About Java functional interface
Expired collection of java
Predicted Features of Java
Java, about 2D arrays
[Java] Significance of serialVersionUID
About class division (Java)
[Java] Stream Collectors notes
About disconnect () of HttpURLConnection
About [Java] [StreamAPI] allMatch ()
About Java StringBuilder class
[Java Silver] Summary of points related to lambda expressions
[For beginners] Quickly understand the basics of Java 8 Lambda
NIO.2 review of java
Review of java Shilber
java neutral lambda expression 1