-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP07.java
38 lines (33 loc) · 1014 Bytes
/
P07.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package lists;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Class for string manipulation.
* Flatten list of strings,
*/
public final class P07 {
private P07() {
}
/**
* Transform a list, possibly holding lists as elements into a 'flat' list
* by replacing each list with its elements (recursively).
*
* @param inputList mixed lists of items
* @param <T> type of item
* @return single list of item
*/
@SuppressWarnings("unchecked")
public static <T> List<T> flatten(final List<?> inputList) {
if (inputList.isEmpty()) {
return Collections.emptyList();
}
return inputList.stream()
.flatMap(obj -> obj instanceof List ? flatten(((List<?>) obj))
.stream()
: Stream.of(obj))
.map(obj -> (T) obj)
.collect(Collectors.toList());
}
}