본문 바로가기
Framwork/Java기초

Chapter 16. 람다 표현식, 열거형, 어노테이션

by 김엉배 2023. 11. 14.
728x90
반응형

목차

1. 람다 표현식(lambda expression)

2. 열거형(enumeration)
3. 어노테이션(annotation)

 

 

1.  람다 표현식(lambda expression)

- 한 번 이상 실행할 수 있도록 만들어 놓는 코드 블록으로 '이름 없는 함수'라고도 한다.

- 지금까지 모든 함수(메소드)는 반드시 이름을 가져야 했지만 람다 표현식은 함수의 역할은 하지만 이름이 없다.


  • 람다 표현식 만들기
    - 기호는 '->'는 람다 연산자라고 부르고 '->' 왼쪽에는 함수의 매개변수를 적고, 오른쪽에는 함수가 반환 값 또는 식을 작성.
(매개변수) -> { 수행되어야 하는 코드 }

 

[예제]

번호 람다 표현식 함수
1 ()  -> 100 int getValue() {
   return 100;
}
2 () -> 100.5 double getValue() {
   return 1.0 / n;
}
3 (n) -> 1.0 / n 또는
 n  -> 1.0 / n
boolean getValue(int n) {
   return (n % 2) == 0;
}
4 (n) -> (n % 2) == 0 또는
 n  -> (n % 2) == 0
boolean getValue(int n) {
   return (n % 2) == 0;
}
5 (n, m) -> n * m int getValue(int n, int m) {
   return n * m;
}

 

 

  • 람다 표현식 사용하기
    - 람다 표현식을 만들었으면 호출해서 사용해야 하는데, 인터페이스가 반드시 필요하다.
    - 인터페이스에 람다 표현식을 수행할 수 있는 추상 메소드를 선언해야 하는데 함수형 인터페이스라고 부른다.

[예제]

interface MyValue1 {
	int getValue();
}

public class Code242 {
	public static void main(String[] args) {
		MyValue1 mv1;
		mv1 = () -> 100; // mv1에 람다 표현식을 넣어 둔다.
		System.out.println(mv1.getValue()); // 람다 표현식이 수행된다.
	}
}
_______________________________________________________________
100

 

  • 블록 람다 표현식
    - 람다 표현식의 (->) 우측에 여러 줄의 실행 코드를 구현하는 경우 중괄호로 묶고 마지막에 세미콜론 삽입
    - 람다 표현식이 여러 줄로 작성되는 경우 '블록 람다 표현식' 이라고 한다.
interface Test {
	int getSum(int n);
}

public class Code243 {
	public static void main(String[] args) {
		Test t = (n) -> {
			int result = 0;
			for(int i=1; i<=n; i++)
				result += i;
			return result;
		}; // 반드시 세미콜론을 넣어야 한다.
		
		System.out.println("sun from 1 to 10 is " + t.getSum(10));
		System.out.println("sun from 1 to 20 is " + t.getSum(20));
		System.out.println("sun from 1 to 30 is " + t.getSum(30));
	}
}
__________________________________________________________________
sun from 1 to 10 is 55
sun from 1 to 20 is 210
sun from 1 to 30 is 465

 

 

 

 

 

2.  열거형(enumeration)

- 여러 개의 상수 데이터를 선언하는데 유용하다.

- 클래스 맴버 중, 상수 데이터는 public static 데이터인데, 이를 한꺼번에 선언할 수 있도록 한다.


enum Cards {
	HEART(10), CLUB(20), SPADE(30), DIAMOND(40);
	
	private int val;
	Cards(int v) { val = v;}
	int getVal() { return val; }
}

public class Code244 {
	public static void main(String[] args) {
		Cards cd;
		System.out.println("Value of SPADE: " + Cards.SPADE.getVal());
		System.out.println("_____________________");
		System.out.println("All values of Cards");
		
		for(Cards c: Cards.values())
			System.out.println(c + " value: " + c.getVal());
	}
}
__________________________________________________________________
Value of SPADE: 30
_____________________
All values of Cards
HEART value: 10
CLUB value: 20
SPADE value: 30
DIAMOND value: 40

 

 

 

 

 

3.  어노테이션(annotation)

- 소스 코드에 코드 외에 부가적인 정보를 넣을 수 있는 기능

- 코드에는 영향을 주지 않고, 주석과 같다.


어노테이션 설명
@Inherited 하위 클래스가 상속받는 상위 클래스임을 알림
@Override 상위 클래스의 메소드를 오버라이딩했음을 알림
@Deprecated 해당 아이템은 더 이상 사용하지 말라는 알림.
@SupperessWarnings 컴파일러에 의해 워닝(warning)이 뜨지 않도록 함
@Functionallneterface 함수형 인터페이스임을 알림

 

class Test2 {
	private String msg;
	Test2(String m) {
		msg = m;
	}
	
	@Deprecated
	String getMsg() {
		return msg;
	}
}

public class Code245 {
	public static void main(String[] args) {
		Test2 t = new Test2("hello");
		System.out.println(t.getMsg());
	}
}
______________________________________________________
hello
728x90
반응형

'Framwork > Java기초' 카테고리의 다른 글

Chapter 15. 스레드  (49) 2023.11.13
Chapter 14. 제네릭스와 컬렉션 프레임워크  (54) 2023.11.12
Chapter 13. 자바 입출력  (57) 2023.10.19
Chapter 12. 예외 처리  (20) 2023.08.15
Chapter 11. 패키지와 클래스들  (16) 2023.08.15