Points To Remember

Program : Flatten a Nested List 

Here we write a Java function that will accept a nested ist upto any level of nesting and flatten this list.
import java.util.List;
import java.util.LinkedList;
import java.util.Scanner;

class FlattenList{

public static void main(String args[]){

CreateList obj = new CreateList();

// Get the nested list sample
List<Object> nestedList = obj.createNestedList();
System.out.println("-----------------------------------");

// Print the nested list
System.out.println("Nested List = " + nestedList);
// Print the sample nested list after flattening the list
System.out.println("Flatten List = " + new FlattenList().flattenList(nestedList));

}

public List<Integer> flattenList(List<Object> nestedList){
List<Integer> flatList = new LinkedList<Integer>();
for(Object obj : nestedList){
if(obj instanceof List) // If the value is a List
for(Integer integer : flattenList((List)obj)) // traverse the returned list and add it to the list.
flatList.add(integer);
if(obj instanceof Integer) // If the value is an integer number add it to list
flatList.add((Integer)obj);
}
return flatList;
}

}
The above program will give the following output
Enter the Nested List
[1,2,3,[4,5],6,[7,[8,9]],10,[11,[12,[13,[14,15],16]]]]
-----------------------------------
Nested List = [1, 2, 3, [4, 5], 6, [7, [8, 9]], 10, [11, [12, [13, [14, 15], 16]]]]
Flatten List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Algorithm

  1. We traverse the List from start to end.
  2. At each element we check if the element is a List or Integer.
    1. If it is a Integer we add it to the output list.
    2. If it is a list we use recursion to flatten this list.
Using the above steps any level of nested list can be flatten.