| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | 
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | 
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | 
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | 
| 30 | 
													Tags
													
											
												
												- java8
 - 스프링부트 채팅서버
 - oauth2
 - 스프링시큐리티
 - 코틀린 클래스
 - SQL 문제풀이
 - springboot
 - SQL
 - 자바 스트림
 - MSA
 - pygame
 - sap ERP
 - 오라클
 - 스프링
 - SAP ABAP
 - LeetCode SQL
 - 프로그래머스
 - 스프링부트
 - javascript
 - Spring
 - js
 - Leetcode
 - 자바스크립트
 - spring boot
 - python
 - mysql
 - oracle
 - kotlin 클래스
 - 구글로그인
 - SQL프로그래머스
 
													Archives
													
											
												
												- Today
 
- Total
 
웅겹살의 프로그래밍 삼매경
[java] stream API 예제 본문
오늘은 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에 대해 알아보자.
'자바(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