How to initialize a list in a single line in Java with a specified value?

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

Examples:

Input: N = 5
Output: [5]

Input: N = GeeksForGeeks
Output: [GeeksForGeeks]

Approach:

  • Get the value N
  • Create an array with this value N
  • Create a List with this array as an argument in the constructor

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to initialize a list
// in a single line with a specified value
  
import java.io.*;
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;
  
        // Create an array of size 1
        T arr[] = (T[]) new Object[1];
  
        // Add the specified value in the array
        arr[0] = N;
  
        // System.out.println(Arrays.toString(arr));
        List<T> list = Arrays.asList(arr);
  
        // return the created list
        return 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));
    }
}

chevron_right


Output:

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



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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.