[Java] Stream

행복한 콩🌳·2023년 3월 30일
0

JAVA

목록 보기
24/26

스트림

  • 자료의 대상과 관계 없이 동일한 연산을 수행
  • 한 번 생성하고 사용한 스트림은 재사용 할 수 없음
// tip: each public class is put in its own file
public class main
{
    // tip: arguments are passed via the field below this editor
    public static void main(String[] args)
    {
        int[] arr = {1,2,3,4,5,};

// 스트림 생성
        IntStream stream = Array.stream(arr);
        int sum = Arrays.stream(arr).sum();
        System.out.print(sum);
// 한 번 생성한 스트림은 최종 연산까지 완료하면 이미 소모되어 버림
        int count = (int)stream.count();
        System.out.print(count));

    }
}
  • 스트림 연산은 기존 자료를 변경하지 않음
  • 스트림 연산은 중간 연산과 최종 연산으로 구분 됨
    * 중간 연산: 어떤 조건을 매칭 시킴
    • 최종 연산: 그 결과를 출력
  • 스트림은 최종 연산까지 모두 수행하고 결과를 확인할 수 있음
public class ArrayListTest
{
    // tip: arguments are passed via the field below this editor
    public static void main(String[] args)
    {
        List<String> sList = new ArrayList<String>();
        sList.add("Tomas");
        sList.add("James");
        
        Stream<String> stream = sList.stream();
        stream.forEach(s -> System.out.println(s));

        // OR

        for(String s : sList){
            System.out.println(s);
        }

    }
}

reduce() 연산

  • 정의된 연산이 아닌 프로그래머가 직접 지정하는 연산을 적용
class CompareString implements BinaryOperator<String>{
    @Override
    public String apply(String s1, String s2){
    if(s1.getBytes().length >= s2.getBytes().length)
                return s1;
            else return s2;}
}

public class reduceTest
{
    // tip: arguments are passed via the field below this editor
    public static void main(String[] args)
    {
        String[] greatings = {"안녕하세요", "Hello", "Good Morning", "반갑습니다."};

        Arrays.stream(greetings).reduce("",(s1,s2)->{
            if(s1.getBytes().length >= s2.getBytes().length)
                return s1;
            else return s2;}
        ));

        String str = Arrays.stream(greetings).reduce(new CompareString()).get();
        System.out.println(str);
    }
}
profile
매일매일 조금씩 모여 숲이 되자🐣

0개의 댓글