Wednesday, October 8, 2025
HomeLanguagesJavaInitialize a list in a single line with a specified value

Initialize a list in a single line 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 using Collection Framework only.

Examples:

Input: N = 5
Output: [5]

Input: N = GeeksForGeeks
Output: [GeeksForGeeks]

Approach:

Below is the implementation of the above approach:




// Java program to initialize a list in a single
// line with a specified value
// using Collection Framework only
  
import java.io.*;
import java.util.*;
import java.util.stream.*;
  
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;
  
        // Generate a Collection with a single value N
        List<T> list = Collections.nCopies(size, N);
  
        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));
    }
}


Output:

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

Most Popular

Dominic
32341 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11874 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6832 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6783 POSTS0 COMMENTS
Umr Jansen
6786 POSTS0 COMMENTS