728x90
    
    
  class LambdaEx {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        int i = 0;
        while (i < 10) {
            list.add(i);
            i++;
        }
        //list의 모든 요소를 출력
        list.forEach(j -> System.out.print(j+","));
        System.out.println();
        
        //list에서 2또는 3의 배수를 제거한다.
        list.removeIf(x -> x % 2 == 0 || x % 3 == 0);
        System.out.println(list);
        list.replaceAll(k -> k * 10); //list의 각 요소에 10을 곱한다.
        System.out.println(list);
        Map<String, String> map = new HashMap<>();
        map.put("1", "1");
        map.put("2", "2");
        map.put("3", "3");
        map.put("4", "4");
        //map의 모든 요소를 {k,v}의 형식으로 출력한다.
        map.forEach((k,v)-> System.out.print("{"+k+","+v+"},"));
        System.out.println();
    }
}- Java8.0에서 추가된 Lambda함수의 예이다.
- 웹개발에 주로 다루는 컬렉션 프레임웤을 좀 더 간단하게 표현할 수 있다.
- 위에 예시에 있는 인터페이스는 밑에 표로 정리했다.
 
인터페이스메서드설명
| Iterable | void forEach(Consumer<T> action) | 모든 요소에 작업 action을 수행 | 
| Collection | boolean removeif(Predicate<E> filter>) | 조건에 맞는 요소를 삭제 | 
| List | void replaceAll(UnaryOperator<E> operator) | 모든 요소를 변환하여 대체 | 
| Map | void forEach(BiConsumer<K,V> action) | 모든 요소에 작업 action을 수행 | 
- Stream에서도 Lambda를 활용할 수 있으니 공부해두면 좋을 듯하다.
728x90
    
    
  'JAVA' 카테고리의 다른 글
| [디자인 패턴]Builder pattern 이란? (0) | 2022.03.22 | 
|---|---|
| Java 8 LocalDateTime 직렬화 역직렬화 오류 (0) | 2022.03.02 | 
| 스트림의 기본 및 간단한 특징 (0) | 2022.02.14 | 
| 람다 함수(with 메서드 참조) (0) | 2022.02.14 | 
| 자바 람다함수(with 함수형 인터페이스) (0) | 2022.02.14 |