different ways to create stream in java with example
Certainly! Here are several different ways to create a Stream in Java along with examples:
1. **From a Collection:**
List<Integer> numbers = [Link](1, 2, 3, 4, 5);
Stream<Integer> streamFromCollection = [Link]();
2. **From an Array:**
String[] array = {"apple", "banana", "orange"};
Stream<String> streamFromArray = [Link](array);
3. **Using [Link]() for Individual Elements:**
Stream<String> streamOfElements = [Link]("apple", "banana", "orange");
4. **Generating Streams with [Link]():**
Stream<String> generatedStream = [Link](() -> "Hello");
5. **Iterating with [Link]():**
Stream<Integer> iteratedStream = [Link](0, n -> n + 2).limit(5);
6. **From a Range of Values:**
IntStream rangeStream = [Link](1, 6);ca
7. **From a Range of Values (Inclusive):**
IntStream rangeClosedStream = [Link](1, 5);
8. **Creating an Empty Stream:**
Stream<Object> emptyStream = [Link]();
How to iterate/print a stream:
To iterate or print the elements of a Stream in Java, you can use various methods provided by the
Stream API. Here are a few common approaches:
1. **Using forEach():**
You can use the forEach() method to perform an action for each element in the stream.
Stream<String> stream = [Link]("apple", "banana", "orange");
[Link]([Link]::println);
2. **Using forEachOrdered():**
This method is similar to forEach(), but it guarantees that the elements are processed in the order
specified by the stream.
Stream<String> stream = [Link]("apple", "banana", "orange");
[Link]([Link]::println);
3. **Converting to List and Using Iterator:**
You can convert the stream to a List and then use an Iterator to iterate over the elements.
Stream<String> stream = [Link]("apple", "banana", "orange");
List<String> list = [Link]([Link]());
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}