-
-
Save BlancosWay/020093c80e080f9cb9c934fa5a4f1236 to your computer and use it in GitHub Desktop.
Flatten a nested list. Java version.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package practice; | |
| import java.util.LinkedList; | |
| import java.util.List; | |
| import static java.util.Arrays.asList; | |
| public class NestList { | |
| public static List<Integer> flatten(List<?> list) { | |
| List<Integer> ret = new LinkedList<Integer>(); | |
| flattenHelper(list, ret); | |
| return ret; | |
| } | |
| public static void flattenHelper(List<?> nestedList, List<Integer> flatList) { | |
| for (Object item : nestedList) { | |
| if (item instanceof List<?>) { | |
| flattenHelper((List<?>) item, flatList); | |
| } else { | |
| flatList.add((Integer) item); | |
| } | |
| } | |
| } | |
| public static void main(String[] args) { | |
| List<Object> nestedList = lst(1, lst(2, lst(3, 4)), lst(5, 6, 7), 8, lst(lst(9, 10))); | |
| List<Integer> flatList = flatten(nestedList); | |
| System.out.println(nestedList); | |
| System.out.println(flatList); | |
| } | |
| private static List<Object> lst(Object... objs) { | |
| return asList(objs); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment