java 람다식/ 메서드 참조/ stream

cornpip·2023년 5월 17일
0

자바

목록 보기
17/19

람다식

메서드 참조

//생성자를 호출하는 람다식도 메서드 참조로 변환할 수 있다. 
Supplier<MyClass> s = () -> new MyClass();
Supplier<MyClass> s = MyClass::new;

//배열 생성의 경우
Function<Integer, int[]> f = x -> new int[x];
Function<Integer, int[]> f = int[]::new;

//매개변수의 개수에 따라 알맞은 함수형 인터페이스를 사용한다.
BiFunction<Integer, String, MyClass> bf = (i, s) -> new MyClass(i,s);
BiFunction<Integer, String, MyClass> bf = MyClass::new;

스트림

    public static void main(String[] args) {
        ArrayList<Integer> t = new ArrayList<>();
        t.add(3); t.add(5); t.add(7);
        Iterator<Integer> tt = t.iterator();

        while (tt.hasNext()){
            System.out.println(tt.next());
        }

        while (tt.hasNext()){
            System.out.println(tt.next());
        }
    }
    결과
    357

iterator는 일회용이다. 컬렉션 요소를 모두 읽고나면 다시 사용할 수 없고 필요하다면 다시 생성해야 한다. 스트림도 마찬가지로 한번 사용하면 닫힌다.

스트림 메서드들 많아서 필요할 때 적절히 검색해 사용하자.

스트림 요소를 소모하는 연산을 최종연산이라 한다.

  • 중간연산 : map(), flatMap()........
  • 최종연산 : reduce(), collect().........
    collect()는 Collector를 구현하거나 미리 작성된 Collectors의 static메서드를 이용한다.

Arrays.sort 최악은 n^2
Collections.sort 최악은 nlogn

어떤 sort든 비교기준(compara)은 당연히 필요한거다.

blabla

자바 기본 패키지 속 클래스, 메서드, 인터페이스 등을 요리조리 만져보면서 상속을 따라가보는건 좋은 공부같다. 메서드 사용법과 함께 클래스를 어떻게 구성하고 제공해야 좋은지 가이드 삼을 수 있다.

profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

0개의 댓글