Some the interview questions i have faced during my career
How we can put list inside another list
Answer: Make a ArrayList which contains ArrayList.
How to create it? Its simple guys
List al = new ArrayList<ArrayList<String>>();
and now you can add List of String inside ArrayList which is putting List inside List
Example:Suppose i have a List having [1,2,3,4...20] and have to add first five element in first position of list then another five on the second position and so on.For this i have to make a List of List.
public class ListInsideList {
public static void main(String[] args) {
// This list be have to insert into List with first fifth element at first index of other list and so on...
List<List<Integer>> newList = new ArrayList<List<Integer>>();
List<Integer> tempList = new ArrayList<Integer>();
List<Integer> originalList = new ArrayList<Integer>();
for (int i = 1; i <= 20; i++) {
originalList.add(i);
}
for(Integer value : originalList){
tempList.add(value);
if(tempList.size()==5)
{
newList.add(tempList);
tempList = new ArrayList<Integer>();
}
}
System.out.println("Final"+newList);
}
}
Output is: Final[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
How we can put list inside another list
Answer: Make a ArrayList which contains ArrayList.
How to create it? Its simple guys
List al = new ArrayList<ArrayList<String>>();
and now you can add List of String inside ArrayList which is putting List inside List
Example:Suppose i have a List having [1,2,3,4...20] and have to add first five element in first position of list then another five on the second position and so on.For this i have to make a List of List.
public class ListInsideList {
public static void main(String[] args) {
// This list be have to insert into List with first fifth element at first index of other list and so on...
List<List<Integer>> newList = new ArrayList<List<Integer>>();
List<Integer> tempList = new ArrayList<Integer>();
List<Integer> originalList = new ArrayList<Integer>();
for (int i = 1; i <= 20; i++) {
originalList.add(i);
}
for(Integer value : originalList){
tempList.add(value);
if(tempList.size()==5)
{
newList.add(tempList);
tempList = new ArrayList<Integer>();
}
}
System.out.println("Final"+newList);
}
}
Output is: Final[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
0 comments :
Post a Comment