CodeGym /Java Blog /Stream API /Java Stream.of() method
Author
John Selawsky
Senior Java Developer and Tutor at LearningTree

Java Stream.of() method

Published in the Stream API group
You've probably already heard that streams in Java are designed to process data. They represent a sequence of elements that can be processed using various operations such as filtering, sorting, reducing, etc. The Stream.of method allows you to get a stream from any data type that implements the Iterable interface. This means with this Stream.of method you can create a stream from strings, numbers, objects, as well as other complex data structures such as collections and arrays. In this article we’ll describe this method and look at several examples of its use.

Stream.of() method in Java

The Stream.of method is used to create a stream from one or more elements. It takes one or more elements as arguments and returns a stream containing those elements. There are two overloaded StreamOf methods. Here is its syntax: static <T> Stream<T> of(T t). This method passes a single element and returns a one element stream of T datatype. static <T> Stream<T> of(T... values). Here we have a variant of the method that passes a few elements of the new stream and returns a stream of T datatype. The Java Stream.of() method creates a stream of finite elements. If you are interested in creating a stream of infinite elements, use Stream.generate() method. Creating a stream using Stream.of() provides the following benefits:
  • Streams allow you to process data more efficiently than traditional for or while loops.
  • Streams simplify code and make it more readable.
  • Streams provide many useful operations that make data processing easier.
Stream.of() aligns with Java's shift towards functional programming paradigms, promoting cleaner and more maintainable code. With the ability to create streams effortlessly, developers can focus on solving complex problems and writing code that is both readable and performant. Now let’s have some examples of using the Stream.of method.

Stream.of method examples

Creating a stream using Stream.of() may be necessary in the following cases:
  • To create a stream from several elements.
  • To create a stream from an array, collection, or other object that supports iteration.
  • To create a stream from the result of another operation.
For example, the following code creates a stream of two numbers:

Stream<Integer> stream = Stream.of(1, 2);

Example 1. Creating a Stream of Strings


import java.util.stream.Stream;

public class StreamOfExample {
    public static void main(String[] args) {
//create a stream of Strings
        Stream<String> stringStream = Stream.of("Johnny", "Ivy", "Rick");
        stringStream.forEach(System.out::println);
    }
}
This code creates a stream of strings and prints each string.

Example 2. Creating a Stream of Integers


import java.util.stream.Stream;

public class StreamOfEx {
       public static void main(String[] args) {
           Integer[] numbers = {2, 7, 18, 28, 45};
           //create a stream of integers 
           Stream<Integer> integerStream = Stream.of(numbers);
           integerStream.forEach(System.out::println);
           Stream<Integer> stream = Stream.of(numbers);

           int sum = stream.reduce(0, (a, b) -> a + b);

           System.out.println("sum = " + sum);

       }

}
This program creates a stream of integers and prints each element. After that we sum up all elements of the stream and print the result out. Here is the output:
2 7 18 28 45 sum = 100

Example 3. Creating a Stream of Objects


import java.util.stream.Stream;

public class StreamOfExample {
    public static void main(String[] args) {
//create a stream of objects
        Stream<Person> personStream = Stream.of(
            new Person("Johnny", 11),
            new Person("Ivy", 13),
            new Person("Rick", 12)
        );
        personStream.forEach(person -> System.out.println(person.getName()));
    }

    static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }
    }
}
In this example, we create a stream of custom Person objects and print the names of each person.

Example 4. Creating a Stream of Arrays


import java.util.stream.Stream;

public class StreamOfExample {
    public static void main(String[] args) {
        Stream<String[]> stream = Stream.of(
            new String[] { "violin", "viola" },
            new String[] { "double bass", "chello" }
        );

        stream.flatMap(array -> Stream.of(array))
              .forEach(System.out::println);
    }
}
This code creates a stream of arrays of strings and then flattens the stream to print each string element.

Conclusions

The Stream.of() method in Java is a general-purpose tool that simplifies the process of creating streams from a sequence of elements. It provides a concise and readable way to work with data, making your code more expressive and functional. If you need to create streams of integers, strings, custom objects, or even arrays, Stream.of() offers a simple solution.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION