15 java concatenation arraylist
我有一个值列表,其中一些可能是列表/集合或单个值.在JavaScript表示法中,它可能看起来像:
const input = [1,2,[3,4], [5,6], 7];
Run Code Online (Sandbox Code Playgroud)
我想得到:
const concatenated = [1,2,3,4,5,6,7];
Run Code Online (Sandbox Code Playgroud)
所以我有这个Java代码:
ArrayList<T> concatenated = new ArrayList<>();
for (T v : input) {
try{
concatenated.addAll((Collection) v);
}
catch (Exception e1){
try{
concatenated.addAll((List) v);
}
catch (Exception e2){
concatenated.add(v);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但那段代码对我来说似乎很糟糕.首先我不知道是否尝试强制转换为List或Collection是否足够 - 是否还有其他类型我应该尝试强制转换?有什么错误我不应该忽略吗?
怎么做对了?
Nam*_*man 13
Exception除非null列表中有值,否则代码不需要这样处理.在你的情况下,只要施放基础就足够了instanceOf:
// Edit: Since the type of the input `Collection` is not bound strictly
List<Object> flatten(Collection<?> input) {
List<Object> concatenated = new ArrayList<>();
for (Object v : input) {
if (v instanceof Collection) {
concatenated.addAll(flatten((Collection<?>) v));
} else {
concatenated.add(v);
}
}
return concatenated;
}
Run Code Online (Sandbox Code Playgroud)
在jshell上进一步使用它给了我这个输出:
jshell> List<Object> list = List.of(1,2,List.of(3,4),List.of(5,6),7)
list ==> [1, 2, [3, 4], [5, 6], 7]
jshell> flatten(list)
$3 ==> [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
:
正如其他人所提到的,使用控制流的异常并不理想.您可以改为使用instanceof运算符来测试元素是否为a Collection.nullpointer的答案显示了一个很好的例子.如果您想要更通用的选项,您还可以执行以下操作:
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public static <E> List<E> deepFlatten(final Iterable<?> iterable, final Class<E> type) {
if (type.isPrimitive() || type.isArray() || Iterable.class.isAssignableFrom(type)) {
throw new IllegalArgumentException(
"type must not denote a primitive, array, or java.lang.Iterable type: " + type);
}
final List<E> result = new ArrayList<>();
for (final Object element : iterable) {
if (element instanceof Iterable<?>) {
result.addAll(deepFlatten((Iterable<?>) element, type)); // recursion
} else if (element != null && element.getClass().isArray()) {
if (element instanceof Object[]) {
result.addAll(deepFlatten(Arrays.asList((Object[]) element), type)); // recursion
} else { // primitive array
final Iterable<?> itrArray = IntStream.range(0, Array.getLength(element))
.mapToObj(index -> Array.get(element, index))::iterator; // method reference
result.addAll(deepFlatten(itrArray, type)); // recursion
}
} else {
/*
* Will throw ClassCastException if any element is not an instance
* of "type". You could also throw a NullPointerException here if
* you don't want to allow null elements.
*/
result.add(type.cast(element));
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这也Iterable通过递归处理"嵌入式"数组以及s.请注意,Map由于含糊不清,它无法处理; 我们应该把键或值弄平 - 或者两者兼而有之?
调用以上内容:
Iterable<?> iterable = List.of(
"A", "B", "C", "D",
List.of("E", "F", List.of("G", "H"), "I", "J"),
"K",
new String[]{"L", "M", "N", "O", "P"},
new String[][]{{"Q", "R"}, {"S", "T"}, {"U"}, {"V"}},
new Object[]{"W", "X"},
"Y", "Z"
);
List<String> flattened = deepFlatten(iterable, String.class);
System.out.println(flattened);
Run Code Online (Sandbox Code Playgroud)
给我:
[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
Run Code Online (Sandbox Code Playgroud)
请注意,这些字母是有序的,因为Lists和数组具有保证的迭代次序.如果您所Iterable包含Set的结果deepFlatten可能不是每次都在相同的顺序.