Until programming beginners can use lambda expressions

A note on how new SIers can use (not say) Java 8 lambda expressions Here is a list of the things that went wrong before you started using it. Roughly speaking, I found it easy to use thanks to Stream.

Lambda type? Have no idea!

Lambda expressions are a feature added since Java 8 You will often hear it along with functional programming and Stream.

Shortly after I understood if and for statements, I learned about the existence of lambda expressions and functional programming.

The frank impression at that time ** "What is this, I have no idea." **

Why don't you understand the lambda expression

In my case, 3 points

** 1. I don't understand the meaning of the word lambda expression ** ** 2. I don't understand the advantages of lambda expressions ** ** 3. I don't know how to write a lambda expression **

Was mentioned.

I don't understand the meaning of the word

The word lambda should be ** unfamiliar to the average person **. Searching for a lambda expression will bring you to the Japanese wiki

Lambda expressions are closely related to lambda calculus and are especially popular in functional languages.

Is written. No, I don't know what lambda calculus is.

I don't understand the benefits

HelloWorldLambda.java


public class Main {
	public static void main(String[] args) {
		Runnable r = () -> System.out.println("Hello World");
		r.run(); // Hello World
	}
}

This is an example of a common Hello World.

I at that time "Usually System.out.println (" Hello World "); Isn't it just good ...?" I was thinking.

That's right. This example is ** intended to use a lambda expression **. This doesn't tell you what the benefits of using a lambda expression are.

I don't know how to write

ExLambda.java


Runnable r = () -> System.out.println("Hello World");

Lambda expressions are written with the grammar (formal argument)-> {process}. Lambda expressions have many parts that can be omitted, which is also a cause for beginners to not understand.

The trouble is that I've never seen Java-> in Java that I've learned so far. Moreover, the content of () is empty even though it is said to be a formal argument in the above example.

Where did these guys {} go? What on earth is this substituting for ** r? ** **

So how did you understand it after all?

I tried using Stream

Lambda expressions are a feature added in Java 8, At the same time, a function called ** Stream API ** has been added.

This is exactly the function for using lambda expressions, Rather, to make the Stream API easier to use It's no exaggeration to say that lambda expressions have been implemented. (I think it includes various factors such as strengthening type inference)

This gave me an image of how to use a lambda expression.

Use .forEach ()

I will explain with a quick example.

ExIterable.java


public class ExIterable {
	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();

		list.add("Apple");
		list.add("Banana");
		list.add("Cherry");

		list.forEach(s -> System.out.println(s));
		// Apple
		// Banana
		// Cherry
	}
}

In this example, the contents of the list with Apple, Banana, and Cherry as elements are output respectively. The lambda expression is used here

list.forEach(s -> System.out.println(s));

That's the part.

Translated into Japanese ** Pack the contents of the list into s one by one, and output the contents of the list one by one with System.out.println (s). ** ** It means that.

Have you ever heard something similar to this?

That's right ** extended for statement **.

for (String s : list) {
	System.out.println(s);
}

The above extended for statement gives the same result as the one using the lambda expression above.

For now, ** lambda expressions are an alternative to extended for statements! I was able to grasp one usage of **. If you know even one place where you can use it, it will be easier to understand from there.

But this alone doesn't really show the benefits of using lambda expressions. Extended for statement is fine! It will become.

Use .mapToInt ()

Now let's display the total of the numbers using a list with ["1", "2", "3"] as elements. Since it is stored in the form of String, it is necessary to parse it to int etc.

ExForEachSum.java


public class ExForEachSum {
	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();

		list.add("1");
		list.add("2");
		list.add("3");

		System.out.println(list); // [1, 2, 3]

		int sum = 0;

		for (String s : list) {
			sum += Integer.parseInt(s);
		}

		System.out.println(sum); // 6

	}
}

It is necessary to prepare variables before the for statement, such as int sum = 0, It takes more time than just outputting as before, such as the need to add in the for statement.

Let's write this using Stream and a lambda expression.

ExStreamSum.java


public class ExStreamSum {
	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();

		list.add("1");
		list.add("2");
		list.add("3");

		System.out.println(list); // [1, 2, 3]

		int sum = list.stream() //Convert List to Stream
				.mapToInt(s -> Integer.parseInt(s)) //Convert Stream to IntStream
				.sum(); //Sum the elements converted to int

		System.out.println(sum); // 6

	}
}

Here, mapToInt is a method that converts the received element to an int and a Stream to an IntStream. And you need to ** how to convert the element to an int ** in that argument. As you may already know, The s-> Integer.parseInt (s) described here is a lambda expression that shows how to transform an element. The String s received as a formal argument is parsed using Integer.parseInt.

You can convert it to an int and pass the element, so try triple it as shown below

int sum = list.stream()
		.mapToInt(s -> {
			int num = Integer.parseInt(s);
			return num * 3;
		}) 
		.sum();
System.out.println(sum); // 18

You can also squeeze the contents of the element to 100 for the time being.

int sum = list.stream()
		.mapToInt(s -> {
			return 100; //I will give you 100 for the time being
		}) 
		.sum();
System.out.println(sum); // 300

I will omit the details, but You can also sort using sorted and Comparator, You can use filter to filter By learning through Stream, I learned how to use lambda expressions.

About Stream API Introduction to Java Stream API Etc. are thought to be detailed.

This is possible with lambda expressions thanks to the ** functional interface **. If you are interested, please see the following article on Qiita. What is a functional interface? (Java)

Instead of writing an object that implements a functional interface, you can write a lambda expression, If you know that, I think you can manage to do it.

I managed to use it a little

I wrote a Qiita article for the first time as a memorandum.

** Local variables are recognized as Final ** Lambda specs plague or ** Exception handling in lambda cannot be caught from the outside ** (naturally due to lambda specifications) There are some points to get stuck, The lambda expression ** destructive power ** is outstanding when used in combination with the Stream API. (Extremely, you can write it even if you don't remember the name or method of the functional interface.)

You can also learn the basic idea of using anonymous functions and lambdas in other languages, so I hope that those who read this article will also try using the lambda expression.

After all, there is no choice but to use and remember ** things that you don't understand.

Recommended Posts

Until programming beginners can use lambda expressions
How to use Java lambda expressions
[For beginners] About lambda expressions and Stream API
Use Java lambda expressions outside of the Stream API
"Inheritance" that even beginners of object-oriented programming can understand
Polymorphism that even beginners of object-oriented programming can understand
Understand Java 8 lambda expressions
About Java lambda expressions
Explain Java 8 lambda expressions
Have fun programming with lambda expressions and a fluid interface