자바(JAVA)/미니 프로젝트 & 기초 공부

Java 기초 다시 공부하기 8주차 - 람다식, 스트림

개발학생 2024. 8. 27. 11:36
반응형

1. 람다 표현식(Lambda Expression)

  • 메서드 대신 하나의 식으로 표현하는 것
  • → 익명 함수 (Anonymous function)
반환타입 메서드이름 (매개변수, ...) {
	실행문
}

public int sum (int x, int y) {
	return x+y;
}
(매개변수, ...) -> {실행문...}
(int x, int y) -> {return x+y;}

1) 장점

  • 코드가 간결해져 가독성이 높아짐
  • 생산성이 높아짐

2) 단점

  • 익명함수이므로 재사용 불가
  • 디버깅이 어려움
  • 재귀함수로는 맞지 않음

* 예제 실습

interface ComputeTool {
    public abstract int compute(int x, int y);

    public abstract int compute2(int x, int y);
}

public class Lambda {
    public static void main(String[] args) {

        ComputeTool cTool1 = new ComputeTool() {
            @Override
            public int compute(int x, int y) {
                return x + y;
            }

            @Override
            public int compute2(int x, int y) {
                return x - y;
            }
        };
        System.out.println(cTool1.compute(1,2));

        // 람다식
//        ComputeTool cTool2 = (x, y) -> {return x + y;};
//        System.out.println(cTool2.compute(1,2));
    }
}

2. 스트림(Stream)

  • 배열, 컬렉션 등의 데이터를 하나씩 참조하여 처리 가능한 기능
  • for문의 사용을 줄여 코드를 간결하게 함

1) Stream 생성

(1) 배열 스트림

String[] arr = new String[]{"a","b","c"};
Stream stream = Arrays.stream(arr);

(2) 컬렉션 스트림

ArrayList list = new ArrayList(Arrays.asList(1,2,3));
Stream stream = list.stream();

2) 중개연산

(1) Filtering

  • filter 내부 조건에 참인 요소들을 추출
IntStream intStream = IntStream.range(1,10).filter(n -> n % 2 == 0);

(2) Mapping

  • map 안의 연산을 요소별로 수행
IntStream intStream = IntStream.range(1,10).map(n -> n + 1);

3) 최종연산

(1) Sum, Average

IntStream.range(1,5).sum()
IntStream.range(1,5).average().getAsDouble()

(2) min, max

IntStream.range(1,5).min().getAsInt();
IntStream.range(1,5).max().getAsInt();

* 예제 실습

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class StreamPro {
    public static void main(String[] args) {
        // 1. 스트림 생성
        // 1-1. 배열 스트림
        System.out.println("=== 배열 스트림 ===");
        String[] arr = new String[]{"a", "b", "c"};

        System.out.println("=== forEach ===");
        for (String item: arr) {
            System.out.println(item);
        }

        System.out.println("=== to Stream ===");
        Stream stream1 = Arrays.stream(arr);
        stream1.forEach(System.out::println);

        // 1-2. 컬렉션 스트림
        System.out.println("=== 컬렉션 스트림 ===");
        ArrayList list1 = new ArrayList(Arrays.asList(1,2,3));
        System.out.println(list1);

        Stream stream2 = list1.stream();
        stream2.forEach(System.out::println);
//        stream2.forEach(num -> System.out.println("num = " + num));

        // 1-3. 스트림 builder
        System.out.println("=== 스트림 builder ===");
        Stream streamBuilder = Stream.builder().add(1).add(2).add(3).build();
        streamBuilder.forEach(System.out::println);

        // 1-4. 스트림 generate
        System.out.println("=== 스트림 generate ===");
        Stream streamGenerate = Stream.generate( () -> "abc").limit(3);
        streamGenerate.forEach(System.out::println);

        // 1-5. 스트림 iterate
        System.out.println("=== 스트림 iterate ===");
        Stream streamIterate = Stream.iterate(10, n -> n * 2).limit(3);
        streamIterate.forEach(System.out::println);

        // 1-6. 기본 타입 스트림
        System.out.println("=== 기본 타입 스트림 ===");
        IntStream intStream = IntStream.range(1,5);
        intStream.forEach(System.out::println);

        // 2. 스트림 중개 연산
        // 2-1. Filtering
        System.out.println("=== Filtering ===");
        IntStream intStream2 = IntStream.range(1,10).filter(n -> n % 2 == 0);
        intStream2.forEach(System.out::println);

        // 2-2. Mapping
        System.out.println("=== Mapping ===");
        IntStream intStream3 = IntStream.range(1,10).map(n -> n + 1);
        intStream3.forEach(n -> System.out.print(n + " "));
        System.out.println();

        // 2-3. Sorting
        System.out.println("=== Sorting ===");
        IntStream intStream4 = IntStream.builder().add(5).add(1).add(3).add(4).add(2).build();
        IntStream intStreamSort = intStream4.sorted();
        intStreamSort.forEach(System.out::println);

        // 3. 최종 연산
        // 3-1. Sum, Average
        System.out.println("=== sum, average ===");
        int sum = IntStream.range(1,5).sum();
        System.out.println("sum = " + sum);
        double average = IntStream.range(1,5).average().getAsDouble();
        System.out.println("average = " + average);

        // 3-2. Min, Max
        System.out.println("=== min, max ===");
        int min =IntStream.range(1,5).min().getAsInt();
        System.out.println("min = " + min);
        int max = IntStream.range(1,5).max().getAsInt();
        System.out.println("max = " + max);

        // 3-3. reduce
        System.out.println("=== reduce ===");
        Stream<Integer> stream3 = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)).stream();
        System.out.println(stream3.reduce((x,y) -> x + y).get());

        // 3-4. forEach
        System.out.println("=== forEach ===");
        IntStream.range(1, 10).filter(n -> n == 5).forEach(System.out::println);
    }
}

 

반응형