EN
Java 8 - create stream
0 points
In this article, we would like to show you how to create a stream in Java 8.
Quick solution:
xxxxxxxxxx
1
Collection<String> collection = Arrays.asList("A", "B", "C");
2
3
// Create stream from the collection
4
Stream<String> stream = collection.stream();
In this example, we present how to create a stream from any type of Collection such as Collection, List or Set.
xxxxxxxxxx
1
import java.util.*;
2
import java.util.stream.Stream;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
Collection<String> collection = Arrays.asList("A", "B", "C");
8
9
// Create stream from the collection
10
Stream<String> streamFromCollection = collection.stream();
11
12
// print elements
13
streamFromCollection.forEach(System.out::println);
14
}
15
}
Output:
xxxxxxxxxx
1
A
2
B
3
C
In this section, we present how to create a stream from specified values such as Strings or Integers.
xxxxxxxxxx
1
import java.util.stream.Stream;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Stream<String> streamOfLetters = Stream.of("A", "B", "C");
7
8
// print elements
9
streamOfLetters.forEach(System.out::println);
10
}
11
}
Output:
xxxxxxxxxx
1
A
2
B
3
C
xxxxxxxxxx
1
import java.util.stream.Stream;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Stream<Integer> streamOfLetters = Stream.of(1, 2, 3);
7
8
// print elements
9
streamOfLetters.forEach(System.out::println);
10
}
11
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
In this example, we present how to create a stream from an array using Arrays.stream()
method.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.stream.Stream;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String[] letters = new String[]{"A", "B", "C", "D"};
8
Stream<String> streamOfArray = Arrays.stream(letters);
9
10
// print elements
11
streamOfArray.forEach(System.out::println);
12
}
13
}
Output:
xxxxxxxxxx
1
A
2
B
3
C
4
D
In this example, we present how to create a stream from part of the array using Arrays.stream()
with the following syntax:
xxxxxxxxxx
1
Arrays.stream(array, indexStart, indexEnd);
Practical example:
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.stream.Stream;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String[] letters = new String[]{"A", "B", "C", "D"};
8
Stream<String> streamOfArray = Arrays.stream(letters, 0, 2);
9
10
// print elements
11
streamOfArray.forEach(System.out::println);
12
}
13
}
Output:
xxxxxxxxxx
1
A
2
B