It's going to be one day 🍀

안녕하세요! 매일 매일 공부하려고 노력하는 백엔드 개발자 지망생의 공부 흔적입니다.

Back-End/Java # 교육

[Java 교육] LIFO,FIFO 컬렉션/람다식 (다시 복습 필수 - 람다식)

2jin2 2024. 2. 16. 16:15

[공부 내용 정리]

LIFO : Last in First Out

나중에 넣은 객체가 먼저 빠져나가는 자료구조.

Stack (후입선출, LIFO)

스택은 마지막에 넣은 객체가 가장 먼저 빠지는 자료구조임.

Stack<E> stack = new Stack<E>();
package chapter11;

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("coin1");
        stack.push("coin2");
        stack.push("coin3");
        stack.push("coin4");

        System.out.println(stack.peek()); // 맨 위 객체를 가져옴.
        System.out.println(stack.peek());
        System.out.println(stack.peek());
        System.out.println(stack.peek());
        System.out.println("---------------------------");

        System.out.println(stack.pop()); // coin4부터 빠져나옴.
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

FIFO : First in First Out

처음에 넣은 객체가 먼저 빠져나가는 자료구조.

Queue (선입선출, FIFO)

큐는 앞서 들어간 데이터가 먼저 출력이 되는 자료구조임.


컬렉션 복습 Quiz2

리스트 안에 있는 숫자 개수세서 Map으로 저장하는 문제


람다식

람다식 : 함수(메서드)를 간단한 식으로 표현하는 방법

람다식은 (매개변수) -> {실행코드} 형태로 작성됨. 마치 함수 정의 형태를 띠고 있지만 런타임 시점에 인터페이스의 익명 구현 객체로 생성됨.

(타입 매개변수, ...) -> { 실행문; ...; }

-> 화살표 기호는 매개 변수를 이용해서 중괄호{}를 실행한다는 뜻으로 해석하면 된다. 

int max(int v1, int v2) {
		return v1 > v2 ? v1 : v2;
}
(int v1, int v2) -> v1 > v2 ? v1 : v2

-> 반환값이 있는 경우에는 식이나 값만 적고 return 문도 생략 가능! 세미콜론도 제거 가능!

 

하나의 매개변수, 하나의 실행문

a -> System.out.println(a)

-> 괄호 생략 가능, 중괄호 생략 가능.

 

* 매개 변수가 없을 경우

() -> { 실행문 .. }

-> 빈 괄호를 반드시 사용해야함.

 

* 중괄호 안에 return 문만 있을 경우

(x, y) -> x + y;

-> return 문을 사용하지 않고 다음과 같이 작성.


함수형 인터페이스 (@FunctionalInterface)

함수형 인터페이스는 단 하나의 추상 메소드만 선언된 인터페이스.

@FunctionalInterface
public interface MyFuntionalInterface {
    public void method();
    public void method2();    // 컴파일 오류 발생
}

→ 어노테이션이 없더라도 하나의 추상 메소드만 있다면 모두 함수형 인터페이스. 실수로 두 개 이상의 추상 메소드를 선언하는 것을 방지하고 싶다면 붙여주는 것이 좋음.

 

매개 변수와 리턴값이 없는 람다식

매개 변수와 리턴값이 없는 추상 메소드를 가진 함수형 인터페이스

@FunctionalInterface
public interface MyFunctionalInterface {
    void method();
}

MyFunctionalInterface finter = () -> { ... }

람다식이 대입된 인터페이스의 참조변수는 다음과 같이 method()를 호출할 수 있음.

finter.method();

ex)

public class MyFunctionalInterfaceExample {

    public static void main(String[] args) {
        MyFunctionalInterface finter;

        finter = () -> {
            String str = "method call 1";
            System.out.println(str);
        };
        finter.method();

        finter = () -> {
            System.out.println("method call 2");
        };
        finter.method();

        finter = () -> System.out.println("method call 3");
        finter.method();
    }
}

<실행 결과>

method call 1
method call 2
method call 3

 

매개 변수가 있는 람다식

매개 변수가 있고 리턴값이 없는 추상 메소드를 가진 함수형 인터페이스.

@FunctionalInterface
public interface MyFunctionalInterface2 {
    void method(int x);
}

MyFunctionalInterface finter = (x) -> { ... };

다음과 같이 method()를 호출할 수 있음. 매개값으로 5를 주면 람다식의 x 변수에 5가 대입되고, x는 중괄호 안에 있는 실행문에서 사용됨.

finter.method(5);

ex)

public class MyFunctionalInterfaceExample2 {

    public static void main(String[] args) {
        MyFunctionalInterface2 finter2;

        finter2 = (x) -> {
            int result = x * 5;
            System.out.println(result);
        };
        finter2.method(2);

        finter2 = (x) -> {
            System.out.println(x * 5);
        };
        finter2.method(2);

        finter2 = x -> System.out.println(x * 5);
        finter2.method(2);
    }
}

<실행결과>

10
10
10

 

리턴값이 있는 람다식

@FunctionalInterface
public interface MyFunctionalInterface3 {
    int method(int x, int y);
}

MyFunctionalInterface fi = (x, y) -> { ...; return 값; }

만약 중괄호 { }에 return문만 있고, return문 뒤에 연산식이나 메소드 호출이 오는 경우라면 다음과 같이 작성할 수 있음.

MyFunctionalInterface fi = (x, y) -> {
		return x + y;
}

=

MyFunctionalInterface fi = (x, y) -> x + y;

ex)

public class MyFunctionalInterfaceExample4 {
    public static void main(String[] args) {
        MyFunctionalInterface3 finter3;

        finter3 = (x, y) -> {
            int result = x + y;
            return result;
        };
        System.out.println(finter3.method(2, 5));
        
        finter3 = (x, y) -> {
            return x + y;
        };
        System.out.println(finter3.method(2, 5));
        
        finter3 = (x, y) -> x + y;
        System.out.println(finter3.method(2, 5));
    }
}

<실행결과>

7
7
7