For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** lambda expressions **.
[Introduction to Java Table of Contents] -Variables and types ・ Type conversion -Variable Scope -String operation -Array operation ・ Operator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handling ・ About lambda expression ← Now here ・ About Stream API
The functional interface was implemented by using an anonymous class (anonymous class). The source code was not readable and tended to be redundant.
The ** lambda expression ** solves such problems. It is a syntax introduced from Java8, and the same implementation as using an anonymous class (anonymous class) has become possible in a simple and highly readable state.
** Lambda expression syntax **
(Argument of method to implement)-> {Processing};
Let's compare with a simple example how simple and readable it actually became.
First, implementation in an anonymous class (anonymous class).
Anonymous class (anonymous class)
//Self-made functional interface
interface Greet {
String sayHello(String name);
}
public class Lambda {
public static void main(String[] args) {
//Create an instance of an anonymous class that implements the Greet interface
Greet case1 = new Greet(){
//Override abstract method sayHello
public String sayHello(String name) {
return name + "San, Hello!";
}
};
//Pass the string to the implemented sayHello method
String tanaka = case1.sayHello("tanaka");
System.out.println(tanaka); //Mr. tanaka, Hello! Is output
}
}
Then implement a similar process with a lambda expression
.
Lambda expression
//Self-made functional interface
interface Greet {
String sayHello(String name);
}
public class Lambda {
public static void main(String[] args) {
//Implement Greet interface with lambda expression and instantiate
Greet case2 = (String name) -> { return name + "San, Hello!"; };
//Pass the string to the implemented sayHello method
String suzuki = case2.sayHello("suzuki");
System.out.println(suzuki); //Mr. suzuki, Hello! Is output
}
}
It can be overridden without writing new Greet () and the method name of the abstract method in it.
This is because the functional interface has only one abstract method
, so ** lambda expressions can determine which method to implement **.
In addition, it is possible to omit it further only in specific cases.
before
Greet case2 = (String name) -> { return name + "San, Hello!"; };
after
Greet case2 = (name) -> { return name + "San, Hello!"; };
Since the method argument type is determined when the functional interface is declared, it can be omitted to `without specifying the argument type at the time of implementation.
before
Greet case2 = (String name) -> { return name + "San, Hello!"; };
after
Greet case2 = name -> { return name + "San, Hello!"; };
If there is only one argument, ()
can be omitted. However, if there is no argument, there are multiple arguments, or even if there is only one argument, the type cannot be omitted.
before
Greet case2 = (String name) -> { return name + "San, Hello!"; };
after
Greet case2 = name -> name + "San, Hello!";
If the process is one sentence, {}
can be omitted. Also, if {}
is omitted, return
can be omitted.
You can write it simply!
The previous example was using a self-made functional interface, Here are some examples of functional interfaces provided as a java.util.function package.
1.Function<T, R>
Takes an argument of type T and returns a value of type R. The method is R apply (T t).
Function example
Function<Integer, String> funcTest = number -> number + "is";
String resutlt = funcTest.apply(19);
System.out.println(resutlt); //19
2.Consumer<T>
Receives an argument of type T. The method is void accept (T t).
Consumer example
Consumer<String> weather = str -> System.out.println("How is the weather today" + str);
weather.accept("It's rain"); // 今日の天気はIt's rain
3.Predicate<T>
Receives an argument of type T. The method is boolean test (T t).
Predicate example
Predicate<String> check = str -> 5 < str.length();
boolean result = check.test("Mitarashi dumpling");
System.out.println(result); // true
boolean result2 = check.test("Mame Daifuku");
System.out.println(result2); // false
4.Supplier<T>
It does not receive anything as an argument. The method is T get ().
Supplier example
Supplier<String> name = () -> "Ichiro Suzuki";
System.out.println(name.get()); //Ichiro Suzuki
5.UnaryOperator<T>
An interface that extends Function. Both the type received as an argument and the type returned are the same. The method is T apply (T t).
Unary Operator example
UnaryOperator<String> breakfast = food -> "After all in the morning" + food;
System.out.println(breakfast.apply("curry")); // 朝はやっぱりcurry
It is also possible to implement the methods provided around the collection framework using lambda expressions. (Multiple objects can be stored, retrieved, and deleted) This is because it receives a functional interface as a method argument. Here are some of them as well.
1.default boolean removeIf(Predicate<? super E> filter)
This method deletes all collection elements that satisfy the specified processing.
removeIf method
List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numbers.removeIf(number -> number % 2 == 0); //Divide by 2 and remove the ones that are 0
System.out.println(numbers); // [1, 3, 5]
2.default void replaceAll(UnaryOperator<E> operator)
A method that performs the specified processing and replaces the elements of the list.
replaceAll method
List<String> names = Arrays.asList("tanaka", "suzuki", "yamada");
names.replaceAll(name -> name.toUpperCase()); //Replace all uppercase
System.out.println(names); // [TANAKA, SUZUKI, YAMADA]
3.default void sort(Comparator<? super E> c)
A method that sorts the list according to the specified order.
sort method
List<Integer> randomNum = Arrays.asList(30, 50, 10, 20, 40);
randomNum.sort((a, b) -> b.compareTo(a)); //Sort in descending order
System.out.println(randomNum); // [50, 40, 30, 20, 10]
randomNum.sort((Integer a, Integer b) -> { return a.compareTo(b); } ); //Sort in ascending order
System.out.println(randomNum); // [10, 20, 30, 40, 50]
4.void forEach(Consumer<? super T> action)
A method that performs the specified action on all elements.
forEach method
List<String> names = Arrays.asList("tanaka", "suzuki", "yamada");
//name+I am trying to output one by one, separated by a half-width space
names.forEach(name -> System.out.print(name + " ")); // tanaka suzuki yamada
I touched on the syntax of lambda expressions. It is convenient that the source code is shortened and only the implementation part needs to be described.
I will summarize the Stream API in a separate article.
java.util.function ** [For beginners] Can't you hear more now? Learn about Java 8 lambda expressions! **
Recommended Posts