Open In App

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

Last Updated : 27 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples:

Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] 

Approach:

  • 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
  
importjava.io.*;
importjava.util.*;
importjava.util.stream.*;
  
classGFG {
  
    // Function to create a List
    // with the specified value
    publicstatic<T> List<T> createList(T N)
    {
  
        // Currently only one value is taken
        intsize = 1;
  
        returnStream
  
            // Generate the Stream
            .generate(String::new)
  
            // Size of the List to be created
            .limit(size)
  
            // Passing the value to be mapped
            .map(s -> N)
  
            // Convert the generated stream into List
            .collect(Collectors.toList());
    }
  
    // Driver code
    publicstaticvoidmain(String[] args)
    {
  
        intN = 1024;
        System.out.println("List with element "
                           + N + ": "
                           + createList(N));
  
        String str = "GeeksForGeeks";
        System.out.println("List with element "
                           + str + ": "
                           + createList(str));
    }
}

Output:

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


Next Article
Practice Tags :

Similar Reads

close