我有两个类
答:
public class A {
private int intValue;
private String stringValue;
public A(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
int getIntValue() {
return intValue;
}
String getStringValue() {
return stringValue;
}
}
和B:
public class B {
private int intValue;
private String stringValue;
B(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
int getIntValue() {
return intValue;
}
String getStringValue() {
return stringValue;
}
}
还有一些相当大的 A 对象数组。
我想转换A[]
至ArrayList<B>
有效地。我知道有几种方法可以做到这一点:
final A[] array = {new A(1, "1"), new A(2, "2")/*...*/};
// 1 - old-school
final List<B> list0 = new ArrayList<>(array.length);
for (A a : array) {
list0.add(new B(a.getIntValue(), a.getStringValue()));
}
// 2 - pretty mush same as 1
final List<B> list1 = new ArrayList<>(array.length);
Arrays.stream(array).forEach(a -> list1.add(new B(a.getIntValue(), a.getStringValue())));
// 3 - lambda-style
final List<B> list2 = Arrays.stream(array).map(a -> new B(a.getIntValue(), a.getStringValue())).collect(Collectors.toList());
// 4 - lambda-style with custom Collector
final List<B> list3 = Arrays.stream(array)
.map(a -> new B(a.getIntValue(), a.getStringValue()))
.collect(Collector.of((Supplier<List<B>>)() -> new ArrayList(array.length), List::add, (left, right) -> {
left.addAll(right);
return left;
}));
据我所知 1 是最有效的。但使用 java 8 的功能可以使其更短。 2 与 1 几乎相同,但带有 foreach
循环被流取代 foreach
。不确定它的有效性。 3是最短路,但默认Collectors.toList()
收集器使用默认ArrayList::new
构造函数,表示 ArrayList
中的数组如果我们有相当大的初始数组,将至少调整一次大小。所以效率不是那么高。而 4,据我了解(虽然从未使用过这种方式)与 3 几乎相同,但在 ArrayList
中为数组分配了单个内存。 。但看起来很丑。
所以,我的问题是。我对这四种方法及其有效性的看法是否正确?还有其他简短有效的方法吗?
最佳答案
你的 #4 可以写得短一点:
final List<B> list4 = Arrays.stream(array)
.map(a -> new B(a.getIntValue(), a.getStringValue()))
.collect(toCollection(() -> new ArrayList<>(array.length)));
您还可以在单独的方法中提取映射:
final List<B> list4 = Arrays.stream(array)
.map(SomeClass::mapA2B)
.collect(toCollection(() -> new ArrayList<>(array.length)));
private static B mapA2B(A a) {
return new B(a.getIntValue(), a.getStringValue());
}
关于java - 将数组 A[] 转换为 ArrayList<B> 的有效且最短的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014738/