Pages

Streams

Stream represents a sequence of objects from a source, which supports aggregate operations.


Basic Points of Streams :
  1. Not a data structure
  2. Designed for lambdas
  3. Do not support indexed access
  4. Can easily be outputted as arrays or lists
  5. Lazy access supported
  6. Parallelizable

Stream.of(val1, val2, val3….)

public class StreamBuilders {
      public static void main(String[] args) {
            Stream stream = Stream.of(1,2,3,4,5,6,7,8,9);
            stream.forEach(p -> System.out.println(p));
      }
}

Stream.of(arrayOfElements)

public class StreamBuilders {
      public static void main(String[] args) {
            Stream stream = Stream.of( new Integer[]{1,2,3,4,5,6,7,8,9} );
            stream.forEach(p -> System.out.println(p));
      }
}

List.stream()

public class StreamBuilders {
      public static void main(String[] args) {
            List list = new ArrayList();
            for(int i = 1; i< 10; i++) {
                  list.add(i);
            }
            Stream stream = list.stream();
            stream.forEach(p -> System.out.println(p));
      }
}

Stream.generate() or Stream.iterate()

public class StreamBuilders {
      public static void main(String[] args) {
            Stream stream = Stream.generate(() -> { return new Date(); });
            stream.forEach(p -> System.out.println(p));
            }
}

String chars or String Tokens (First Model)

public class StreamBuilders {
      public static void main(String[] args) {
            IntStream stream = "12345_abcdefg".chars();
            stream.forEach(p -> System.out.println(p));
      }
}

String chars or String Tokens (Second Model)

public class StreamBuilders {
      public static void main(String[] args) {
            Stream stream = Stream.of("A$B$C".split("\\$"));
            stream.forEach(p -> System.out.println(p));
      }
}