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:
import java.io.*;
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> List<T> createList(T N)
{
int size = 1 ;
List<T> list = Collections.nCopies(size, N);
return list;
}
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]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Jan, 2020
Like Article
Save Article