-
-
Notifications
You must be signed in to change notification settings - Fork 689
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
updating method signature in flatten array
- Loading branch information
1 parent
919b7f7
commit fb2e4ba
Showing
3 changed files
with
11 additions
and
21 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
"aadityakulkarni", | ||
"FridaTveit", | ||
"jackattack24", | ||
"jagdish-15", | ||
"jmrunkle", | ||
"jtigger", | ||
"kytrinyx", | ||
|
29 changes: 9 additions & 20 deletions
29
exercises/practice/flatten-array/.meta/src/reference/java/Flattener.java
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,17 @@ | ||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.List; | ||
|
||
final class Flattener { | ||
class Flattener { | ||
|
||
List flatten(final List nestedList) { | ||
if (nestedList.isEmpty()) { | ||
return new ArrayList<>(); | ||
} else { | ||
final List result = new ArrayList(); | ||
|
||
final Object head = nestedList.get(0); | ||
final List tail = nestedList.subList(1, nestedList.size()); | ||
|
||
if (head instanceof List) { | ||
result.addAll(flatten((List) head)); | ||
} else { | ||
result.add(head); | ||
List<Object> flatten(List<?> list) { | ||
List<Object> flattenedList = new ArrayList<>(); | ||
for (Object element: list) { | ||
if (element instanceof List<?> listAsElement) { | ||
flattenedList.addAll(flatten(listAsElement)); | ||
} else if (element != null) { | ||
flattenedList.add(element); | ||
} | ||
|
||
result.addAll(flatten(tail)); | ||
result.removeAll(Collections.singleton(null)); | ||
return result; | ||
} | ||
return flattenedList; | ||
} | ||
|
||
} |
This file contains 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