빗썸 테크 아카데미/TIL

3일차

민철킹 2021. 8. 20. 21:24

2일차에 이해서 함수형 프로그래밍 진행

 

 

Predicate

 

filterList를 그대로 사용하면서 새로운 Predicate를 만들 수 있다.

리스트 중 "민"이 포함된 문자열만 담아 반환

 

리스트 중 짝수만 담아 반환

 

UnaryOperator(단항 연산자)

 

BinaryOperator(다항 연산자)

Enum을 활용

 


메서드 참조(::)

 

위, 아래 모두 같은 기능을 하는 동일한 코드이다. 여기서 threadGenerator의 Thread::new가 바로 메서드 참조이다.

 

메서드 참조를 통해 불필요한 매개변수를 제거하고 간단하게 나타낼 수 있다.

Thread::new // == new Thread()

Math::pow // == (foo1, foo2) -> Math.pow(foo1, foo2) 

Function<String, Boolean> func = (a) -> Object.equals(a); // == Function<String, Boolean> func = obj::equals(a);

oper = (n) -> Math.abs(n); // == oper = Math::abs;

 


Stream

 

컬렉션의 원소를 하나씩 꺼내 람다식으로 처리할 수 있는 반복자이다. for문(Iterator)과 비슷한 역할을 하지만 코드가 더 간결하며 내부 반복자를 통해 병렬처리가 쉬워진다.

stream 또한 chain형식으로 메서드를 연속해서 작성할 수 있다.

// list : [1,2,3]
list.stream().forEach(foo -> System.out.println(foo));

for (int foo : list) {
	System.out.println(foo);
}

두 스타일은 동일한 기능을 수행하지만 stream을 사용하면 람다식을 사용할 수 있기 때문에 훨씬 더 가독성이 좋은 코드를 작성할 수 있다.

 

 


Optional

 

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

 

Optional (Java Platform SE 8 )

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orEl

docs.oracle.com

 

@Data
class Address {
        private final String street;
        private final String city;
        private final String zipcode;
}

@Data
class Member {
        private final Long id;
        private final String name;
        private final Address address;
}

@Data
class Order {
        private final Long id;
        private final Date date;
        private final Member member;
}

주문한 회원이 살고있는 도시를 뽑아내는 메서드를 Optional을 사용해서 구현하였다.

 

Optional은 간단히 말자하면 Null을 감싸는 래핑 클래스 정도로 생각하면 될 것이다. 가장 고질적인 문제인 NullPointerException을 해결하기 위해 자바8부터 등장하였다.

 

위의 공식 문서를 참조하면 어렵지않게 이해할 수 있을 것이다.

 

 

반응형

'빗썸 테크 아카데미 > TIL' 카테고리의 다른 글

6일차  (0) 2021.08.27
5일차  (0) 2021.08.25
4일차  (0) 2021.08.24
2일차  (0) 2021.08.20
1일차  (2) 2021.08.19