java

스트림 2

improve 2024. 2. 15. 12:20

● Stream of

package org.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class Main8 {
    public static void main(String[] args) {
        Stream.of(11, 22, 33, 44, 55)
                .forEach(System.out::println); //매서드 참조 

        System.out.println();

        Stream.of("so simple")
                .forEach(System.out::println);

        System.out.println();

        Stream.of(Arrays.asList("11", "aaa", "bbb"), Arrays.asList("test"))
                .forEach(System.out::println);
    }
}

 

스트림 생성을 직접 전달 

 

●range, rangeClosed

package org.example;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main8 {
    public static void main(String[] args) {
        Stream.of(11, 22, 33, 44, 55)
                .forEach(System.out::println); //매서드 참조

        System.out.println();

        Stream.of("so simple")
                .forEach(System.out::println);

        System.out.println();

        Stream.of(Arrays.asList("11", "aaa", "bbb"), Arrays.asList("test"))
                .forEach(System.out::println);

        System.out.println();
        IntStream.range(1, 10).forEach(System.out::println); //range 는 범위 (1~9)
        System.out.println();
        IntStream.rangeClosed(1, 10).forEach(System.out::println); // rangeClosed 도 범위 (1~10)

        System.out.println();
        System.out.println(IntStream.range(1, 10).filter(value -> value%2 ==1 ).sum());
        System.out.println();
        System.out.println(IntStream.rangeClosed(1, 10).sum());


    }
}

 

 

● stream 의 정렬

 

package org.example;

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main9 {
    public static void main(String[] args) {
        Stream.of(11, 55, 66, 22, 33)
                .sorted()
                .forEach(System.out::println);

        System.out.println();

        Stream.of(11, 55, 33, 22, 99)
                .sorted((o1, o2) -> o2 - o1) // 내림차순
                .forEach(System.out::println);

        System.out.println();

        IntStream.of(1,3,5,7,9)
                .peek(System.out::println);

        System.out.println();

        IntStream.of(1, 3, 5, 7, 9)
                .peek(System.out::println)
                .sum();

        System.out.println();

        IntStream.of(1, 3, 5, 7, 9)
                .peek(System.out::println)
                .forEach(System.out::println);

    }
}