본문 바로가기

# 02/Java

[윤성우 열혈자바] 30-1. 스트림의 생성과 연결

반응형

스트림의 생성: 스트림 생성에 필요한 데이터를 직접 전달


static <T> Stream<T> of(T t)


static <T> Stream<T> of(T...values)


public static void main(String[] args) {

   Stream.of(11, 22, 33, 44)               //  개의 값으로 이뤄진 스트림 생성

      .forEach(n -> System.out.print(n + \t));

   System.out.println();

 

   Stream.of(So Simple")              // 하나의 String 인스턴스로 이뤄진 스트림 생성

      .forEach(s -> System.out.print(s + "\t"));

   System.out.println();

 

   List<String> sl = Arrays.asList("Toy", "Robot", "Box");

   Stream.of(sl)                               // 하나의 컬렉션 인스턴스로 이뤄진 스트림 생성 - 원소 1개임!!

      .forEach(w -> System.out.print(w + "\t"));

   System.out.println();

}









스트림의 생성: 다양한 of 메소드들


static DoubleStream of(double...values)   // DoubleStream 메소드

static DoubleStream of(double t)    // DoubleStream 메소드

 

static IntStream of(int...values)   // IntStream 메소드

static IntStream of(int t)    // IntStream 메소드

 

static LongStream of(long...values)   // LongStream 메소드

static LongStream of(long t)    // LongStream 메소드

 

static IntStream range(int startInclusive, int endExclusive)    // IntStream 메소드 (1, 9) 1~8

static IntStream rangeClosed(int startInclusive, int endInclusive)   // IntStream 메소드 (1, 9) 1~9

 

static LongStream range(Long startInclusive, Long endExclusive)   // LongStream 메소드

static LongStream rangeClosed(Long startInclusive, Long endInclusive)   // LongStream 메소드-Double형은 존재X








병렬 스트림으로 변경


Stream<T> parallel()    // Stream<T> 메소드

DoubleStream parallel()      // DoubleStream 메소드

IntStream parallel()     // IntStream 메소드

LongStream parallel() // LongStream 메소드



public static void main(String[] args) {

   List<String> ls = Arrays.asList("Box", "Simple", "Complex", "Robot");

   Stream<String> ss = ls.stream(); // 스트림 생성

   

   BinaryOperator<String> lc = (s1, s2) -> {

      if(s1.length() > s2.length())

         return s1;

      else

         return s2;

   };

 

   String str = ss.parallel() // 병렬 스트림 생성

                  .reduce("", lc);

   System.out.println(str);

}


Complex








스트림의 연결


static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

static DoubleStream concat(DoubleStream a, DoubleStream b)

static IntStream concat(IntStream a, IntStream b)

static LongStream concat(LongStream a, LongStream b)


public static void main(String[] args) {

   Stream<String> ss1 = Stream.of("Cake", "Milk");

   Stream<String> ss2 = Stream.of("Lemon", "Jelly");

 

   // 스트림을 하나로 묶은  출력

   Stream.concat(ss1, ss2)

         .forEach(s -> System.out.println(s));

}




반응형