Initialize a list in a single line with a specified value using Java Stream

Given a value N, the task is to create a List having this value N in a single line in Java using Stream.


Input: N = 5
Output: [5]

Input: N = GeeksForGeeks
Output: [GeeksForGeeks]


  • Get the value N
  • Generate the Stream using generate() method
  • Set the size of the List to be created as 1 using limit() method
  • Pass the value to be mapped using map() method
  • Convert the generated stream into List using Collectors.toList() and return it by collecting using collect() method

Below is the implementation of the above approach:





// Java program to initialize a list in a single
// line with a specified value using Stream
import java.util.*;
class GFG {
    // Function to create a List
    // with the specified value
    public static <T> List<T> createList(T N)
        // Currently only one value is taken
        int size = 1;
        return Stream
            // Generate the Stream
            // Size of the List to be created
            // Passing the value to be mapped
            .map(s -> N)
            // Convert the generated stream into List
    // Driver code
    public static void main(String[] args)
        int N = 1024;
        System.out.println("List with element "
                           + N + ": "
                           + createList(N));
        String str = "GeeksForGeeks";
        System.out.println("List with element "
                           + str + ": "
                           + createList(str));



List with element 1024: [1024]
List with element GeeksForGeeks: [GeeksForGeeks]

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :


Please write to us at to report any issue with the above content.