>  기사  >  Java  >  Java 람다 표현식

Java 람다 표현식

WBOY
WBOY원래의
2024-08-30 16:16:201004검색

Lambda 표현식은 Java8에 추가된 새로운 기능입니다. 기본적으로 기능적 인터페이스의 모든 인스턴스를 설명합니다. 구현은 하나의 추상 함수만 포함하고 기능적 인터페이스를 구현하는 방식으로 작동합니다. Java 8 Lambda Expression은 메소드 인수를 생성하거나 전체 코드를 데이터로 간주할 수 있습니다. 특정 클래스가 없는 함수, 즉 추상 클래스를 구현할 수 있습니다. 이 표현식은 다음 개체에 전달될 수 있으며 필요할 때마다 실행할 수 있습니다. 람다 표현식은 함수처럼 간주될 수 있으며 다른 함수처럼 매개변수를 받아들일 수 있습니다.

구문:

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

lambda_operator -> body

Java 람다 표현식의 매개변수

lambda_operator에 전달되는 매개변수는 다음과 같습니다.

  • # 0 매개변수: 이 매개변수는 함수의 인수를 전달할 수 없음을 의미하며, 이는 아래와 같이 표시됩니다.
  • (): System.out.println(“Zerolambda 인수”);
  • # 하나의 매개변수: 이 매개변수는 함수의 인수 중 하나를 전달할 수 있음을 의미하며, 이는 아래와 같이 표시됩니다.
  • (p): System.out.println(“인수 1개: ” + p);
  • # 다중 매개변수: 이름에서 알 수 있듯이 이 매개변수는 두 개 이상의 매개변수를 연산자에 전달하는 데 사용할 수 있으며 다음과 같이 표현됩니다.
  • (q1, q2): System.out.println(“다중 인수: ” + q1 + “, ” + q2);

Java 람다 표현식이 필요한 이유는 무엇입니까?

Lambda 표현식은 Java 8과 함께 등장했으며 실행을 위해 전달할 수 있는 코드 블록의 모든 복잡한 실행을 변환하고 단순화했습니다. 이는 다른 많은 프로그래밍 언어에서 사용하는 매우 일반적인 기능이며 Java 8도 마찬가지입니다. 도입 후 Java의 초기 기능은 먼저 객체를 생성한 다음 전략적인 디자인 패턴을 만드는 것과 같이 객체를 전달해야 합니다. 그러나 람다 표현식은 기능적 인터페이스 구현을 향상시키기 위한 부가 가치이기 때문에 위에서 설명한 문제의 구세주가 되었습니다. 함수에 전달할 매개변수가 0개, 1개 및 여러 개 있는 프로그램 본문을 가리키는 Lambda_operator 함수를 사용하여 구현을 단순화했습니다. 또한 정의된 클래스에 속하지 않고 생성되는 함수를 사용합니다. 전체적으로 데이터로 간주되는 함수의 메소드 인수로 기능을 채택할 수 있는 아주 좋은 기능을 가지고 있습니다.

Java 8의 Lambda 표현식은 매우 강력하고 매력적입니다. 최종 출력을 위해 기능적 인터페이스와 관련된 객체를 변환하는 것이 좋습니다.

Java 람다 표현식은 어떻게 작동하나요?

모든 표현식에는 숨겨진 작업 패턴이 있으므로 Lambda 표현식처럼 다음과 같이 표시되는 일부 작업 패턴도 보유합니다.

(int arg_a, String arg_b)
{System.out.println("two arguments"+ arg_a+" and "+arg_b);}

이 두 인수 int arg_a 및 String arg_b는 인수가 0개, 인수가 1개 또는 인수가 2개 이상(예: 여러 인수)인 인수 목록을 구성합니다. 인수 목록인 이러한 인수는 화살표 토큰의 도움을 받아 람다 식의 본문으로 전달됩니다. 인수 목록이 포함된 이 화살표 토큰은 람다 본문을 계속 따릅니다. 또한 이 형식의 람다 식은 구현을 위해 기능적 인터페이스를 추가로 활용합니다. 그러나 여러 인수 목록인 경우 대괄호나 코드 블록을 닫아야 하며 익명 함수의 반환 유형은 다음과 같은 경우 블록 또는 void의 코드를 반환해야 하는 값 유형과 동일합니다. 반환되지 않거나 그에 대한 가치가 없습니다.

Java 람다 표현식 구현 예시

다음은 Java 람다 표현식의 예입니다.

예시 #1

이 프로그램은 람다 표현식을 사용하지 않고 직사각형 크기를 인쇄하기 위한 추상 클래스를 생성하지 않고도 인터페이스 실행을 보여줍니다.

코드:

interface Shapes
{
public void rectangle();
}
public class WithoutLambdaExpression {
public static void main(String[] args) {
int size=15;
Shapes wd=new Shapes(){
public void rectangle()
{
System.out.println("Get the shape" +  size );
}
};
wd.rectangle();
}
}

출력:

Java 람다 표현식

예시 #2

이 프로그램은 람다 표현식을 사용하여 기능적 인터페이스를 생성하여 모양에 필요한 출력을 제공하는 방법을 보여줍니다.

코드:

interface Shapes{
public void Rectangle();
}
public class UsinglmbdaExpression {
public static void main(String[] args) {
int size=20;
Shapes r8=()->
{
System.out.println("Shapes of all sizes "+ size);
};
r8.Rectangle();
}
}

출력:

Java 람다 표현식

Example #3

This program is used to illustrate the Lambda Expression for Java 8 by not passing any parameter implemented just with the function parameter and the associated abstract classes of the implemented functional interface as shown.

Code:

interface SomethingFishy{
public String strange();
}
public class LambdaWithNoArg{
public static void main(String[] args) {
SomethingFishy k=()->{
return "Very Strange View.";
};
System.out.println(k.strange());
}
}

Output:

Java 람다 표현식

Example #4

This program illustrates the lambda Expression with the implementation of functional parameters, thereby passing the single parameter from the function of the interface and the lambda expression associated with it.

Code:

interface JuicyFruit{
public String juicy(String name);
}
public class SinglParamLambda
{
public static void main(String[] args)
{
JuicyFruit jf1=(name)->{
return "Kiwi, "+name;
};
System.out.println(jf1.juicy("orange"));
JuicyFruit jf2= name ->{
return "Mango, "+name;
};
System.out.println(jf2.juicy("Pineapple"));
}
}

Output:

Java 람다 표현식

Example #5

This program is used to illustrate the Multiple parameter lambda Expression with the functional interface of division and its values to be divided using the class’s div function.

Code:

interface Division{
int div(int p,int q);
}
public class MultiParamLambdaExpression{
public static void main(String[] args) {
Division div1=(p,q)->(p/q);
System.out.println(div1.div(20,40));
Division div2=(int p,int q)->(p/q);
System.out.println(div2.div(400,600));
}
}

Output

Java 람다 표현식

Note: Lambda expressions are exclusively used to implement the functional interfaces, and they can contain any type of argument such as zero, two or multiple.

Conclusion

Lambda Expression introduced with Java 8 has simplified the execution of the block of code using the array operator and operator arrow pointing to the lambda body, and then it will be used for implementing the interfaces with the abstract classes associated with each class. Thus, Lambda Expression of Java 8 has really transformed the interface interaction and the implementation of the functions and method easier with the abstract classes.

위 내용은 Java 람다 표현식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 서버소켓다음 기사:자바 서버소켓