자바 스트림(Stream)

웅평·2023년 12월 13일

스트림

  • 스트림은 '데이터의 흐름’이다
  • 배열 또는 컬렉션 인스턴스에 함수 여러 개를 조합해서 원하는 결과를 필터링를 통해서 얻는다
  • 스트림은 한번 필터링을 하면 데이터를 소진한다, 재사용 불가능

생성하기

배열 스트림

public class _05_Stream {
    public static void main(String[] args) {
        // stream 생성
        // Arrays.stream
        int[] scores = {100, 80, 50, 70, 90};
        IntStream scoreStream = Arrays.stream(scores);
    }
}

컬렉션 스트림

 // Collections.stream
        String[] lengs = {"Python", "Java", "C", "C++", "C#"};
        Stream<String> stream = Arrays.stream(lengs);
		List<String> langList = new ArrayList<>();
        langList = Arrays.asList("Python", "Java", "C", "C++", "C#");
        Stream<String> langListStream = langList.stream();
  • asList: 리스트 생성과 동시에 값을 초기화

Stream.of

Stream<String> langOfStream = Stream.of("Python", "Java", "C", "C++", "C#");
  • 값들을 가진 스트림 생성

스트림 사용

중간 연산(Intermediate Operation)

  • 필터링(filter, map, sorted, distinct, skip....)
    최종 연산(Terminal Operation)
  • 필터링을 통해서 최종적으로 얻는 결과물(count, min, max, sum, foreach, anyMatch, allMatch...)
  • 한번만 사용가능

80점 이상인 점수

public class _05_Stream {
    public static void main(String[] args) {
        // stream 생성
        // Arrays.stream
        int[] scores = {100, 80, 50, 70, 90};
        IntStream scoreStream = Arrays.stream(scores);
        
        Arrays.stream(scores).filter(x -> 80 <= x).forEach(x -> System.out.println(x));
        

    }
}

콜론으로 클래스명 메소드명을 구분하면 앞에서 필터링한 데이터가 자동으로 넘어가 같은 기능을 위의 코드와 같은 기능을한다
Arrays.stream(scores).filter(x -> 80 <= x).forEach(System.out::println);

80점 이상인 수

int cnt = (int)Arrays.stream(scores).filter(x -> x >= 90).count();
        System.out.println(cnt);

count가 long를 반환한다

90이상 수들의 합

int s = Arrays.stream(scores).filter(x -> x >= 90).sum();
        System.out.println(s);

정렬

Arrays.stream(scores).filter(x -> x >= 80).sorted().forEach(System.out::println);

sorted()를 통해 정렬

문자열
C로 시작하는 문자열

public class _05_Stream {
    public static void main(String[] args) {
        String[] lengs = {"Python", "Java", "C", "C++", "C#"};
        Stream<String> stream = Arrays.stream(lengs);
        
        Arrays.stream(lengs).filter(x -> x.startsWith("C")).forEach(System.out::println);
    }
}

Java 포함하는 문자열

Arrays.stream(lengs).filter(x -> x.contains("Java")).forEach(System.out::println);

문자열 길이가 4이하의 언어 정렬해서 출력

langList.stream().filter(x -> x.length() <= 4).sorted().forEach(System.out::println);

4글자 이하이면서 C포함

langList.stream().filter(x -> x.length() <= 4).filter(x -> x.contains("C")).forEach(System.out::println);

4글자 이하 문자열 중에 하나라도 C 가 포함되는 문자열이 있는지 확인

boolean anyMatch = langList.stream().filter(x -> x.length() <= 4).anyMatch(x -> x.contains("C"));
        System.out.println(anyMatch);

anyMatch : 하나라도 맞으면 true

3글자 이하 모든 문자열이 C 가 포함되는 확인 여부

boolean allMatch = langList.stream().filter(x -> x.length() <= 3).allMatch(x -> x.contains("C"));
        System.out.println(allMatch);

allMatch : 모두 맞아야 true

4글자 이하, C 글자를 포함하는 문자열 뒤에 새로운 문자열 추가

langList.stream().filter(x -> x.length() <= 4).filter(x -> x.contains("C"))
                .map(x -> x + " 어려워요").forEach(System.out::println);

map를 통해서 결과 뒤에 어려워요 를 붙여서 출력

C라는 포함하는 문자열 소문자로

langList.stream().filter(x -> x.contains("C")).map(String::toLowerCase).forEach(System.out::println);

대문자는 toUpperCase

c라는 글자를 포함하는 언어를 소문자로 변경하여 리스토로 저장

List<String> langListOfC = langList.stream().filter(x -> x.contains("C"))
                .map(String::toLowerCase)
                .collect(Collectors.toList());

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

참고
나도코딩 유튜브

0개의 댓글