람다란?
- 람다라는 단어는 수학 람다 대수에서 비롯되었음
- 익명 함수를 의미함
- 함수 지향 프로그래밍에서 자주 쓰이는 기법
- 이름 처럼 익명 함수를 의미하기 때문 함수를 선언과 구현이 대부분 같이 되는 것이 특징임
package Chapter20;
public interface Printer {
void Print();
}
인터페이스 선언 - 단일 함수 지향
package Chapter21;
import Chapter20.Printer;
public class LambdaEx01 {
public static void main(String[] args) {
//{}생략 버전, 실행문이 한 줄 일 때
Printer printer = () -> System.out.println("Hello World");
printer.Print();
}
}
() -> {} 기본 형태로 작동 됨
package Chapter21;
import java.util.function.Function;
public class LambdaEx03 {
public static void main(String[] args) {
//Fucntion 은 <T,K> -> T는 입력값, K는 결과값을 리턴하는 함수형 인터페이스임
Function<Integer,String> function = (x) -> x + "age";
System.out.println(function.apply(10));
}
}
Function인터페이스를 사용해서 <입력,리턴>을 제네릭으로 구현하여서, 단순하게 함수를 람다식으로 사용할 수 있음
사용부에서는 function.apply 함수 사용해야함
System.out::println
매개변수가 단일 값이면 람다로부터 들어오는 변수를 바로 받아서 쓸수 있음 -> 메서드 참조식
스트림이란?
- 배열이나 리스트 같은 것을 스트림 타입으로 변경하여서 필요한 함수들을 유용하게 사용하는 방법
- 스트림은 휘발성을 띄고 있기 때문에 사용한 후 Cunsumer 클래스로 인하여 메모리에서 날라가는 특징이 있기 때문에
관리 측에서 유용하고, 사용할 때는 새롭게 스트림을 만들어 줘야함
- 대신 메모리를 적재 후 삭제하기 때문에 for이나 while에서 스트림을 과도 하게 사용하면 성능 측면에서 문제가 될 수 있음
- 내부 기능 함수는 대부분 체이닝 기법이 사용 되기 때문에 다수 사용 시 라인 정리 필수
package Chapter21;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TravelCustomerMain {
public static void main(String[] args) {
List<TravelCustomer> customers = new ArrayList<TravelCustomer>(Arrays.asList
(
new TravelCustomer("제니", 23, 28000),
new TravelCustomer("리사", 20, 35000),
new TravelCustomer("지수", 18, 25000)
));
System.out.println("=========고객 명단 순서대로 출력=========");
customers.stream().map(TravelCustomer::getName).forEach(System.out::println);
System.out.println("=========고객의 여행 비용 합계 출력=========");
System.out.println("합 계 : " + customers.stream().mapToInt(TravelCustomer::getPrice).sum());
System.out.println("=========20세 이상의 고객의 이름을 정렬하여 출력=========");
customers.stream()
.filter(x -> x.getAge() >= 20)
.map(TravelCustomer::getName)
.sorted()
.forEach(System.out::println);
}
}
filter는 조건에 맞는 값만 찾아줌
map은 특정 값만 가진 데이터만 리턴
sorted 정렬
등등...
람다식과 함께 쓰면 괜찮을 듯
예외처리
- 예외 상황 처리
- 예외 관련 계층 구조
- RuntimeException은 언 체크드 타입이라서 컴파일 시 에러가 되지 않고, 런타임 시 에러 분출
- 나머지는 체크드 타입이라서 컴파일시에서도 에러 체크 됌
- Try, Catch, Finally 구문 사용 가능
try {
}
catch(Exception e){
}
기본적인 구조
try {
}
catch(Exception e){
}
finally{
}
try 또는 catch 문 진행 후 -> finally 구문
public class ExceptionEx09 {
public static void main(String[] args) {
try {
method1();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
static void method1() throws Exception {
method2();
}
static void method2() throws Exception {
method3();
}
static void method3() throws Exception {
throw new Exception("응 예외야~"); //예외 발생
}
}
throws 를 해주면 호출한 위 단에서 처리해주는 걸로함
'Java' 카테고리의 다른 글
250224_ 자바 GUI 기능들.. (0) | 2025.02.24 |
---|---|
250213_자바 FileIOStream 클래스들 (0) | 2025.02.13 |
250211_Java 중첩 클래스 (0) | 2025.02.11 |