[JAVA8] Stream API 사용 예제

걸러내기

  • Filter(Predicate)
  • 예) 이름이 3글자 이상인 데이터만 새로운 스트림으로

변경하기

  • Map(Function) 또는 FlatMap(Function)
  • 예) 각각의 Post 인스턴스에서 String title만 새로운 스트림으로

생성하기

  • generate(Supplier) 또는 Iterate(T seed , UnaryOperator)
  • 예) 10부터 1씩 증가하는 무제한 숫자 스트림
  • 예) 랜덤 int 무제한 스트림

제한하기

  • limit(long) 또는 skip(long)
  • 예) 최대 5개의 요소가 담긴 스트림을 리턴한다.
  • 예) 앞에서 3개를 뺀 나머지 스트림을 리턴한다.
public class ClassForStreamAPIPractice {
    private Integer id;
    private String title;
    private boolean closed;

    public ClassForStreamAPIPractice(Integer id, String title, boolean closed) {
        this.id = id;
        this.title = title;
        this.closed = closed;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isClosed() {
        return closed;
    }

    public void setClosed(boolean closed) {
        this.closed = closed;
    }

    @Override
    public String toString() {
        return "ClassForStreamAPIPractice{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", closed=" + closed +
                '}';
    }
}
public class AppForStreamAPIPractice {
    public static void main(String[] args) {
        List<ClassForStreamAPIPractice> springClasses = new ArrayList<>();
        springClasses.add(new ClassForStreamAPIPractice(1 , "spring boot" , true));
        springClasses.add(new ClassForStreamAPIPractice(2 , "spring data jpa" , true));
        springClasses.add(new ClassForStreamAPIPractice(3 , "spring mvc" , false));
        springClasses.add(new ClassForStreamAPIPractice(4 , "spring core" , false));
        springClasses.add(new ClassForStreamAPIPractice(5 , "rest api development" , false));

        System.out.println(" spring으로 시작하는 수업 ");
        springClasses.stream()
                .filter(oc -> oc.getTitle().startsWith("spring"))
                .forEach(oc -> System.out.println(oc.getId()));
        // 필터에 걸린 객체를 리스트로 받기
        List<ClassForStreamAPIPractice> exam1List = springClasses.stream()
                 .filter(oc -> oc.getTitle().startsWith("spring"))
                 .collect(Collectors.toList());

        exam1List.forEach(System.out::println);

        System.out.println(" close되지 않은 수업 ");
        springClasses.stream()
                .filter(oc -> !oc.isClosed())
                .forEach(oc -> System.out.println(oc.getId()));

        // 스태틱 메서드와 메서드 레퍼런스 활용
        springClasses.stream()
                .filter(Predicate.not(ClassForStreamAPIPractice::isClosed))
                .forEach(oc -> System.out.println(oc.getId()));

        // 필터에 걸린 객체를 리스트로 받기
        List<ClassForStreamAPIPractice> exam2List = springClasses.stream()
                .filter(Predicate.not(ClassForStreamAPIPractice::isClosed))
                .collect(Collectors.toList());

        exam2List.forEach(System.out::println);


        System.out.println(" 수업 이름만 모아서 스트림 만들기 ");
        // 중개 오퍼레이터인 map은 객체를 map으로 받아들여 나갈때는 다른 타입으로 변경할 수 있다.
        springClasses.stream()
                        .map(ClassForStreamAPIPractice::getTitle)
                        .forEach(System.out::println);


        List<ClassForStreamAPIPractice> javaClasses = new ArrayList<>();
        javaClasses.add(new ClassForStreamAPIPractice(6 , "The Java , Test" , true));
        javaClasses.add(new ClassForStreamAPIPractice(7 , "The Java , Code manipulation" , true));
        javaClasses.add(new ClassForStreamAPIPractice(8 , "The Java , 8 to 11" , false));

        List<List<ClassForStreamAPIPractice>> keesunEvents = new ArrayList<>();
        keesunEvents.add(springClasses);
        keesunEvents.add(javaClasses);

        System.out.println(" 두 수업 목록에 들어 있는 모든 수업 아이디 출력 ");
        // 메서드 레퍼런스
        keesunEvents.forEach(oc -> {
            oc.forEach(System.out::println);
        });
        // flatMap
        // forEach에는 리스트안의 객체 타입으로 들어간다.
        keesunEvents.stream().flatMap(Collection::stream)
                .forEach(System.out::println);

        System.out.println(" 1부터 1씩 증가하는 무제한 스트림 중에서 앞에 10개 빼고 최대 10개 까지만 ");
        Stream.iterate(1 , i  -> i + 1)
                .skip(10)
                .limit(10)
                .forEach(System.out::println);

        System.out.println(" 자바 수업 중에 Test가 들어 있는 수업이 있는지 확인 ");
        boolean test = javaClasses.stream().anyMatch(oc -> oc.getTitle().contains("Test"));
        System.out.println(test);

        System.out.println(" 스프링 수업 중에 제목에 spring이 들어간 제목만 모아서 List로 만들기 ");
        List<String> titleList = springClasses.stream()
                                        .map(ClassForStreamAPIPractice::getTitle)
                                        .filter(t -> t.contains("spring"))
                                        .collect(Collectors.toList());
        titleList.forEach(System.out::println);

        System.out.println(" 스프링 수업 중에 제목에 spring이 들어간 객체를 모아서 List로 만들기 ");
        List<ClassForStreamAPIPractice> objList = springClasses.stream()
                                            .filter(oc -> oc.getTitle().contains("spring"))
                                            .collect(Collectors.toList());
        objList.forEach(System.out::println);
    }
}

 

 

 

더 자바, Java 8 - 인프런

자바 8에 추가된 기능들은 자바가 제공하는 API는 물론이고 스프링 같은 제 3의 라이브러리 및 프레임워크에서도 널리 사용되고 있습니다. 이 시대의 자바 개발자라면 반드시 알아야 합니다. 이

www.inflearn.com

 

'기록 > JAVA' 카테고리의 다른 글

[JAVA8] Date 와 Time  (0) 2021.01.14
[JAVA8] Optional  (0) 2021.01.12
[JAVA8] Stream  (0) 2021.01.10
[JAVA8] API의 기본 메서드와 스태틱 메서드  (0) 2021.01.10
[JAVA8] 인터페이스 기본 메서드와 스태틱 메서드  (0) 2021.01.10