BlueHarmel
BlueHarmel Devlog
BlueHarmel
전체 방문자
오늘
어제

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 분류 전체보기 (330)
    • Book (11)
    • Dev (29)
      • ArtCon (0)
      • ESTsoft 오르미 (29)
    • Study (290)
      • Web (18)
      • AWS (2)
      • 알고리즘 (1)
      • GameDev (1)
      • 정보처리기사 (201)
      • English (1)
      • Mathematics (24)
      • 머신러닝 (7)
      • 딥러닝 (10)
      • 네트워크 보안 (5)
      • R (4)
      • 컴퓨터 네트워크 (6)
      • 데이터베이스 (8)
      • 데이터 통신 (0)
      • 운영체제 (2)
      • TIL (0)
    • Project (0)
      • 개인 (0)
      • 단체 (0)

인기 글

hELLO · Designed By 정상우.
BlueHarmel

BlueHarmel Devlog

람다식
Dev/ESTsoft 오르미

람다식

2024. 2. 23. 10:59

1. 람다식이란? 람다식 작성하기

  • 설명 보기
    • 람다식 : 함수를 간단한 식으로 표현하는 방법
      • 익명 함수를 생성하기 위한 식
    Runnable runnable = new Runnable() {  // 익명 구현 객체
    		public void run() { ... }
    }
    Runnable runnable = () -> { ... };   // () 이후 : 람다식

2. 기본 문법

  • 설명 보기
    (타입 매개변수, ...) -> { 실행문; ...; }
    
    (a) -> { System.out.println(a); }
    • 소괄호 : 중괄호 블록을 실행하기 위해 필요한 값을 제공
    
    a -> System.out.println(a)
    // 매개 변수가 없어도 빈 괄호를 적어줘야 한다.
    () -> { 실행문 .. }
    //함수에 return 문만 있는 경우, 다음과 같이 사용
    (x, y) -> x + y;

    람다식으로 변경해보기 연습

    • 메서드 → 람다식으로 변경
    int max(int a, int b) {
        return a > b ? a : b;
    }
    
    // (a, b) -> a > b ? a : b
    int print(String name, int i) {
        System.out.println(name+"="+i);
    }
    
    // (name, i) -> System.out.println(name+"="+i);
    int square(int x) {
        return x * x;
    }
    
    // x -> x * x

3. 함수형 인터페이스

  • 설명 보기
    • 함수형 인터페이스 (@FunctionalInterface)
      • 단 하나의 추상 메소드만 선언된 인터페이스
        @FunctionalInterface
        public interface MyFuntionalInterface {
            public void method();
            public void method2();    // 컴파일 오류 발생
        }
      • @FunctionalInterface 어노테이션은 선택사항
    • 함수형 인터페이스 타입의 참조변수로 람다식을 참조할 수 있다.
    • 매개변수가 없는 경우
      MyFunctionalInterface f = () -> {
      		System.out.println("람다식 출력");
      }
    • 매개변수가 있는 경우
    • 리턴값이 있는 경우

4. java.util.function 패키지

  • 설명 보기
    • 자주 사용되는 다양한 함수형 인터페이스를 제공하는 패키지
    1. Runnable
      1. 매개 변수와 리턴값이 모두 없는 경우에 사용
      package java.lang;
      
      @FunctionalInterface
      public interface Runnable {
          public abstract void run();
      }
      Runnable r = () -> System.out.println("출력문 테스트");
      r.run();    // "출력문 테스트" 
    1. Supplier<T>
      1. 매개변수는 없고, 리턴값(타입)이 있는 경우에 사용
      package java.util.function;
      
      @FunctionalInterface
      public interface Supplier<T> {
          T get();
      }
      Supplier<String> s = () -> "리턴되는 값";
      String result = s.get();
      System.out.println(result);   // "리턴되는 값"
    1. Consumer<T>
      1. Supplier과 반대
      1. 매개변수는 있지만 리턴타입이 없는 경우에 사용
      package java.util.function;
      
      @FunctionalInterface
      public interface Consumer<T> {
          void accept(T t);
      }
      Consumer<String> c = (a) -> System.out.println(a);
      c.accept("consumer");
    1. Function<T,R>
      1. 하나의 매개변수를 받아서 하나의 결과를 리턴
      package java.util.function;
      
      @FunctionalInterface
      public interface Function<T, R> {
          R apply(T t);
      }
      Function<Integer, String> f = a -> String.valueOf(a);
      Function<String, Integer> f2 = b -> {
          return Integer.valueOf(b) + 100;
      };
    1. Predicate<T>
      1. 조건식을 표현할때 사용
      1. 매개변수는 하나, 리턴타입은 boolean
      package java.util.function;
      
      @FunctionalInterface
      public interface Predicate<T> {
          boolean test(T t);
      }
      Predicate<String> isEmptyStr = s -> s.length()==0;
      String str = "";
      if (isEmptyStr.test(str)) { // if(s.length()==0)
      		System.out.println("This is an empty String.")
      }
      
      // 스트림에서 filter메소드 내부에는 Predicate 타입이 들어감
      List<Integer> list = Arrays.asList(1,2,3,4,5);
      list.stream()
      		.filter(x -> x%2==0)
      		.collect(Collectors.toList()); // [2,4] 

5. 메소드 참조

  • 설명 보기
    • 메소드를 참조해서 매개 변수의 정보 및 리턴 타입을 알아내어, 람다식에서 불필요한 매개 변수를 제거하는 것
    • 람다식은 하나의 메소드만 호출하므로 메소드 참조로 더 간단히 바꿀 수 있다.
      종류람다메소드 참조
      정적(static) 메소드 참조(x) → ClassName.method(x)ClassName::method
      인스턴스 메소드 참조 (obj, x) → obj.method(x)ClassName::method
    • 메소드 참조도 람다식과 마찬가지로 인터페이스의 익명 구현 객체로 생성되므로 타겟 타입인 인터페이스의 추상 메소드가 어떤 매개변수를 가지고, 리턴타입이 무엇인가에 따라 달라진다.
    • 메소드 참조는 정적 메소드 / 인스턴스 메소드를 참조할 수 있고, 생성자 참조도 가능하다

    • 정적 메소드 및 인스턴스 메소드 참조
      • 정적 메소드 :
        클래스::메소드 
      • 인스턴스 메소드 :
        참조변수::메소드 
        public class MethodReferenceExample {
            public static void main(String[] args) {
                IntBinaryOperator operator;
        
                // 정적 메소드 참조
                operator = (x, y) -> Calculator.staticMethod(x, y);
                System.out.println("결과1: " + operator.applyAsInt(1, 2));
        
                operator = Calculator::staticMethod;
                System.out.println("결과2: " + operator.applyAsInt(3, 4));
        
                // 인스턴스 메소드 참조
                Calculator calculator = new Calculator();
                operator = (x, y) -> calculator.instanceMethod(x, y);
                System.out.println("결과3: " + operator.applyAsInt(5, 6));
        
                operator = calculator::instanceMethod;
                System.out.println("결과4: " + operator.applyAsInt(7, 8));
            }
        }
        public class Calculator {
            public static int staticMethod(int x, int y) {   // 정적 메소드
                return x + y;
            }
        
            public int instanceMethod(int x, int y) {   // 인스턴스 메소드
                return x + y;
            }
        }
    • 매개변수의 메소드 참조
      (a, b) -> { a.instanceMethod(b); }
      //대소문자 구분없이 비교
      
      public class ArgumentMethodReferencesExample {
          public static void main(String[] args) {
              ToIntBiFunction<String, String> function;
      
              function = (a, b) -> a.compareToIgnoreCase(b);
              print(function.applyAsInt("Java8", "JAVA8"));
      
              function = String::compareToIgnoreCase;
              print(function.applyAsInt("Java8", "JAVA8"));
          }
      
          public static void print(int order) {
              if (order < 0) {
                  System.out.println("사전순으로 먼저 옵니다.");
              } else if (order == 0) {
                  System.out.println("동일한 문자열");
              } else {
                  System.out.println("사전순으로 나중에 옵니다.");
              }
          }
      }
    • 생성자 참조
      (a, b) -> { return new 클래스(a, b); }
      클래스 :: new

'Dev > ESTsoft 오르미' 카테고리의 다른 글

스트림  (0) 2024.02.23
이팩티브 자바-인터페이스  (0) 2024.02.23
컬렉션  (0) 2024.02.23
리스트  (0) 2024.02.23
제네릭  (0) 2024.02.23
    BlueHarmel
    BlueHarmel
    Interested in Mathematics, Foreign Language, and "Programming"

    티스토리툴바