Java

자바 스트림(Stream), 람다(Lambda)

Karla Ko 2024. 3. 12. 14:10
728x90

Stream 생성

배열

Arrays 클래스의 static 메소드인 stream()에 배열 인스턴스를 전달

 int[] i = {1,2,3,4,5};
 IntStream istm = Arrays.stream(i);

컬렉션

컬렉션 인스턴스를 대상으로 디폴트 메소드 stream()을 호출

 List<String> s = Arrays.asList("a", "b", "c");
 Stream<String> stm = s.stream();

데이터 직접 전달

Stream클래스 혹은 IntStream 등의 기본 자료형 스트림의 static 메소드인 of()에 stream에 넣고 싶은 데이터들을 전달

 Stream<Integer> istm = Stream.of(1,2,3);
 IntStream istm = IntStream.of(1,2,3);

 

중간 연산

  • filter(Predicate<T> p) : boolean test(T t)
  • map(Function<T, R> f)
  • peek(consumer<T> c) : void accept(T t)
  • sorted(Comparator<T> c) : int compare(T o1, T o2)

 

최종연산

  • forEach(Consumer<T> c): void accept(T t)
  • toArray()
  • collect()
    • collect(Collectors.toList()): 리스트로 만들 때 유용
    • collect(Collectors.joining(””)): string으로 만들 때 유용
  • sum(), count(), average(), min(), max()
    • IntStream, LongStream, DoubleStream 인스턴스 대상으로만 사용이 가능
    • average(), min(), max() 메소드들은 결과값으로 Optional 리턴 : ifPresent(Consumer<T> c), get(), orElse() 사용
  • allMatch(), anyMatch(), noneMatch()

 

예시

Test 클래스의 이너클래스 Detail에 name이라는 필드가 있을 때(getter, settger 생략)

class Test {
    private final Detail detail;
    private final int state;


    class Detail {
        private final String name;
    }

}

state가 1이 아닌 것 리스트 구하기

List<Test> filteredList = testList.
    .stream().filter(test -> test.getState!=1) // state가 1이 아닌 것 필터
    .collect(Collectors.toList());

name 필드 상위 3개 구하기

public List<Map.Entry<String, Long>> findFrequentName(List<Test> testList) {

    Map<String, Long> map = testList.stream() // 스트림으로 변환
            .map(webLog -> webLog.getDetail().getName()) // 이름 추출
            .collect(Collectors.groupingBy(key -> key, Collectors.counting())); 
            // 이름을 키값으로 카운트 값

    // 상위 3개
    return map.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder())) // 내림차순 정렬
            .limit(3).collect(Collectors.toList());
}

문자열을 스트림 처리한 뒤 리스트의 첫번째가 이넘중 하나에 포함되는지 체크하기

enum AlphaType { 
    A,B,C,D
}

String path = "A/test/468/";

String temp = Arrays.stream(path.split("/"))
	.filter(p -> !p.isEmpty())
        .collect(Collectors.toList())
        .get(1);
        
// enum 체크 
if (Arrays.stream(AlphaType.values()).anyMatch(v -> v.name().equals(temp))) { 
    return;
}

 

람다식

  • 함수(메서드)를 간단한 식으로 표현하는 방법
  • (인자 목록) -> { 로직 }
// 메서드
void foo() {
    System.out.println("TEST");
}

// 람다식
() -> {
    System.out.println("TEST");
};
728x90