Friday, November 9, 2018

Java 8 - Streams - How to Create a Stream?

Greetings!

It is easy to guess that we can create a Stream using a collection. Actually it is one of the ways to create a Stream.

Stream from collections


Stream<Employee> stream = employees.stream();


Stream from values

Using static Stream.of() we can create a stream using given values.

Stream<String> countryStream = Stream.of("Sri Lanka", "India", "Pakistan");
Stream<Integer> integerStream = Stream.of(1, 2, 3);
Stream<Employee> employeeStream = Stream.of(new Employee());


Stream from arrays

Arrays class has Arrays.stream() static method to convert given array into a stream.

int[] intArray = { 1, 2, 3, 4, 5 };
IntStream intStream = Arrays.stream(intArray);
String[] stringArray = { "Hello", "World" };
Stream<String> stringStream = Arrays.stream(stringArray);


Stream from files

Files class has static methods to open a file as a stream.

// from a file
try (Stream<String> linesStream = Files.lines(Paths.get("pom.xml"))) {
   linesStream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

// print files in current working directory
try (Stream<Path> paths = Files.list(Paths.get(""))) {
    paths.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}


Stream from numeric ranges


// Inclusive. Up to 100
IntStream.rangeClosed(1, 100).forEach(System.out::println);

// Exclusive. Up to 99
IntStream.range(1, 100).forEach(System.out::println);

// With Steps
IntStream.iterate(0, i -> i + 2).limit(50).forEach(System.out::println);



No comments:

Post a Comment