본문 바로가기

자바

람다

 

package lambda;

import java.util.ArrayList;

public class Main01 {
	public static void main(String[] args) {
		
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		
		numbers.add(5);
		numbers.add(9);
		numbers.add(8);
		numbers.add(1);
		numbers.forEach( (n) -> {System.out.println(n); } );
		
		for(int i = 0; i < numbers.size(); i++) {
			System.out.println(numbers.get(i));
		}
	}
}

 

Lambda expressions can be stored in variables if the variable's type is an interface which has only one method.

The lambda expression should have the same number of parameters and the same return type as that method.

Java has many of these kinds of interfaces built in, such as the Consumer interface(found in the java.util. package) used by lists.

package lambda;

import java.util.ArrayList;
import java.util.function.Consumer;

public class MyClass {

	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		
		numbers.add(5);
		numbers.add(9);
		numbers.add(8);
		numbers.add(1);
		
		Consumer<Integer> method = (n) -> { System.out.println(n); };
		numbers.forEach(method);
	}
}

 

To use a lambda expression in a method, the method should have a parameter with a single-method interface as its type. Calling the interface's method will run the lambda expression :

package lambda;

public class Main02 {

	public static void main(String[] args) {
		StringFunction exclaim = (s) -> s + "!";
		StringFunction ask = (s) -> s + "?";
		printFormatted("Hello", exclaim);
		printFormatted("Hello", ask);
	}
	
	public static void printFormatted(String str, StringFunction format) {
		String result = format.run(str);
		System.out.println(result);
	}
}

interface StringFunction {
	String run(String str);
}

Hello!
Hello?

'자바' 카테고리의 다른 글

정규식  (0) 2020.11.11
synchronized  (0) 2020.11.09
java의 .properties 파일 읽기  (0) 2020.11.09
new 연산자  (0) 2020.11.09
java null  (0) 2020.11.09