찌니의 프로그래밍 삼매경

[java] stream API 예제 본문

자바(java)

[java] stream API 예제

zzI니☆ 2021. 1. 24. 16:27
728x90

오늘은 stream API를 예제로 통해 알아보는 시간이다.

 

난 고기를 좋아하니까 고기종류를 예를들어 예제를 작성한다.

id, title, soldOut(품절여부)

public class MeatType {

    private Integer id;
    private String title;
    private boolean soldOut;

    public MeatType(Integer id, String title, boolean soldOut){
        this.id = id;
        this.title = title;
        this.soldOut = soldOut;
    }

    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 isSoldOut() {
        return soldOut;
    }

    public void setSoldOut(boolean soldOut) {
        this.soldOut = soldOut;
    }
}

 


1) 특정 문자열(돼지)로 시작하는 대상추출

    public static void main(String[] args) {
        List<MeatType> porkBeaf = new ArrayList<>();
        porkBeaf.add(new MeatType(1, "돼지삼겹살", true));
        porkBeaf.add(new MeatType(2, "돼지목살", true));
        porkBeaf.add(new MeatType(3, "돼지항정살", false));
        porkBeaf.add(new MeatType(4, "돼지가브리살", false));
        porkBeaf.add(new MeatType(5, "소채끝살", false));

        System.out.println("돼지로 시작하는 고기");
        porkBeaf.stream()
                .filter(v -> v.getTitle().startsWith("돼지"))
                .forEach(v -> System.out.println(v.getId() + " > " + v.getTitle()));
    }

결과


2) boolean(isSoldOut) 으로 판단하여 결과노출

배가고프니까 soldOut이 false인 친구들만 노출하고싶다.

    public static void main(String[] args) {
        List<MeatType> porkBeaf = new ArrayList<>();
        porkBeaf.add(new MeatType(1, "돼지삼겹살", true));
        porkBeaf.add(new MeatType(2, "돼지목살", true));
        porkBeaf.add(new MeatType(3, "돼지항정살", false));
        porkBeaf.add(new MeatType(4, "돼지가브리살", false));
        porkBeaf.add(new MeatType(5, "소채끝살", false));

        System.out.println("\nsoldOut 되지 않은 고기");
        System.out.println("방법 1");
        // 방법 1
        porkBeaf.stream()
                .filter(v -> !v.isSoldOut())
                .forEach(v -> System.out.println(v.getId() + " > " + v.getTitle()));
        // 방법 2 (약간 더 멋있는 방법)
        // ! 대신 Predicate.not() 을 사용하면 간지가 난다.
        System.out.println("\n방법 2");
        porkBeaf.stream()
                .filter(Predicate.not(MeatType::isSoldOut))
                .forEach(v -> System.out.println(v.getId() + " > " + v.getTitle()));
    }

방법 1과 2의 결과는 같다

입맛에 맞는걸로 사용하자.

 


3) 싹다 모아서 steam 만들어 노출하기

    public static void main(String[] args) {
        List<MeatType> porkBeaf = new ArrayList<>();
        porkBeaf.add(new MeatType(1, "돼지삼겹살", true));
        porkBeaf.add(new MeatType(2, "돼지목살", true));
        porkBeaf.add(new MeatType(3, "돼지항정살", false));
        porkBeaf.add(new MeatType(4, "돼지가브리살", false));
        porkBeaf.add(new MeatType(5, "소채끝살", false));

        System.out.println("\n고기종류 모아서 스트림 만들기");
        porkBeaf.stream()
                .map(MeatType::getTitle)
                .forEach(System.out::println);
    }

 


4) List 2개 전부 출력

    public static void main(String[] args) {
        List<MeatType> porkBeaf = new ArrayList<>();
        porkBeaf.add(new MeatType(1, "돼지삼겹살", true));
        porkBeaf.add(new MeatType(2, "돼지목살", true));
        porkBeaf.add(new MeatType(3, "돼지항정살", false));
        porkBeaf.add(new MeatType(4, "돼지가브리살", false));
        porkBeaf.add(new MeatType(5, "소채끝살", false));

        List<MeatType> chickens = new ArrayList<>();
        chickens.add(new MeatType(6, "지코바숯불양념구이", true));
        chickens.add(new MeatType(7, "BBQ황금올리브", true));
        chickens.add(new MeatType(8, "허니콤보", false));

        List<List<MeatType>> meats = new ArrayList<>();
        meats.add(porkBeaf);
        meats.add(chickens);

        System.out.println("\n두 종류의 모든 ID 출력");
        meats.stream()
                .flatMap(Collection::stream)
                .forEach(v -> System.out.println(v.getId()));

    }

 


5) 10부터 1씩 증가하는 무제한 스트림 중에서 앞에 10개 빼고 최대 10개 까지만 출력

    public static void main(String[] args) {
    
        System.out.println("\n10부터 1씩 증가하는 무제한 스트림 중에서 앞에 10개 빼고 최대 10개 까지만 출력");
        Stream.iterate(10, i -> i + 1)
                .skip(10)
                .limit(10)
                .forEach(System.out::println);

    }

 


6) 특정 문자 포함 여부확인

    public static void main(String[] args) {
    
        List<MeatType> chickens = new ArrayList<>();
        chickens.add(new MeatType(6, "지코바숯불양념구이", true));
        chickens.add(new MeatType(7, "BBQ황금올리브", true));
        chickens.add(new MeatType(8, "허니콤보", false));
        chickens.add(new MeatType(9, "BBQ자메이카통다리", true));

        System.out.println("\n치킨 중에 허니가 들어있는 치킨이 있는지 확인");
        boolean isHoney = chickens.stream().anyMatch(v -> v.getTitle().contains("허니"));
        System.out.println(isHoney);
        
    }


7) 특정 친구들만 모아서 List로 만들어 출력하기

    public static void main(String[] args) {
        List<MeatType> porkBeaf = new ArrayList<>();
        porkBeaf.add(new MeatType(1, "돼지삼겹살", true));
        porkBeaf.add(new MeatType(2, "돼지목살", true));
        porkBeaf.add(new MeatType(3, "돼지항정살", false));
        porkBeaf.add(new MeatType(4, "돼지가브리살", false));
        porkBeaf.add(new MeatType(5, "소채끝살", false));

        System.out.println("\nporkBeaf 친구들중에 돼지가 들어간 고기만 모아서 List로 만들기");
        List<String> pork = porkBeaf.stream()
                .filter(v -> v.getTitle().contains("돼지"))
                .map(v -> v.getTitle())
                .collect(Collectors.toList());
        pork.forEach(System.out::println);

    }

 


stream API를 알아보았다.

이제 고기를 먹으러 가야겠다.

다음시간에는 Optional에 대해 알아보자.

728x90

'자바(java)' 카테고리의 다른 글

[java] 롬복 lombok 이란?  (0) 2022.06.16
[java] 자바 java Iterator  (0) 2022.06.15
[java] List 종류와 정리  (0) 2022.03.31
[java] Set 종류와 정리  (0) 2022.03.30
[java] Map 종류와 정리  (0) 2022.03.29
Comments