Java 将集合转换为数组的最简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3293946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:48:29  来源:igfitidea点击:

The easiest way to transform collection to array?

javaarrayscollectionstransformation

提问by Roman

Suppose we have a Collection<Foo>. What is the best (shortest in LoC in current context) way to transform it to Foo[]? Any well-knownlibraries are allowed.

假设我们有一个Collection<Foo>. 将其转换为 的最佳(在当前上下文中 LoC 中最短)的方法是什么Foo[]?允许使用任何知名库。

UPD: (one more case in this section; leave comments if you think it's worth to create another thread for it): What about transforming Collection<Foo>to Bar[]where Barhas constructor with 1 parameter of type Fooi.e. public Bar(Foo foo){ ... }?

UPD:(多了一个在本节的情况下,发表评论,如果你认为它的价值创造另一个线程它):关于什么转变Collection<Foo>Bar[]那里Bar与1个型参数有构造函数Foo,即public Bar(Foo foo){ ... }

采纳答案by doublep

Where xis the collection:

x收藏在哪里:

Foo[] foos = x.toArray(new Foo[x.size()]);

回答by Andreas Dolk

If you use it more than once or in a loop, you could define a constant

如果您多次或在循环中使用它,您可以定义一个常量

public static final Foo[] FOO = new Foo[]{};

and do the conversion it like

并像这样进行转换

Foo[] foos = fooCollection.toArray(FOO);

The toArraymethod will take the empty array to determine the correct type of the target array and create a new array for you.

toArray方法将采用空数组来确定目标数组的正确类型并为您创建一个新数组。



Here's my proposal for the update:

这是我对更新的建议:

Collection<Foo> foos = new ArrayList<Foo>();
Collection<Bar> temp = new ArrayList<Bar>();
for (Foo foo:foos) 
    temp.add(new Bar(foo));
Bar[] bars = temp.toArray(new Bar[]{});

回答by OscarRyz

For the original see doublepanswer:

原文见doublep答案:

Foo[] a = x.toArray(new Foo[x.size()]);

As for the update:

至于更新:

int i = 0;
Bar[] bars = new Bar[fooCollection.size()];
for( Foo foo : fooCollection ) { // where fooCollection is Collection<Foo>
    bars[i++] = new Bar(foo);
}    

回答by Roman

Here's the final solution for the case in update section (with the help of Google Collections):

以下是更新部分案例的最终解决方案(借助 Google Collections):

Collections2.transform (fooCollection, new Function<Foo, Bar>() {
    public Bar apply (Foo foo) {
        return new Bar (foo);
    }
}).toArray (new Bar[fooCollection.size()]);

But, the key approach here was mentioned in the doublep's answer(I forgot for toArraymethod).

但是,在doublep 的回答中提到了这里的关键方法(我忘记了toArray方法)。

回答by Jules

Alternative solution to the updated question using Java 8:

使用 Java 8 更新问题的替代解决方案:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);

回答by Naman

With JDK/11, an alternate way of converting a Collection<Foo>to an Foo[]could be to make use of Collection.toArray(IntFunction<T[]> generator)as:

与JDK / 11,转换的替代方式Collection<Foo>,以一个Foo[]可利用的Collection.toArray(IntFunction<T[]> generator)为:

Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11


As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0])--

正如@Stuart 在邮件列表(强调我的)中所解释的那样,它的性能应该与现有的性能基本相同Collection.toArray(new T[0])——

The upshot is that implementations that use Arrays.copyOf() are the fastest, probably because it's an intrinsic.

It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.

结果是使用Arrays.copyOf() 的实现是最快的,可能是因为它是一个内在的.

它可以避免对新分配的数组进行零填充,因为它知道整个数组内容将被覆盖。无论公共 API 是什么样子,这都是正确的。

The implementation of the API within the JDK reads:

JDK 中 API 的实现内容如下:

default <T> T[] toArray(IntFunction<T[]> generator) {
    return toArray(generator.apply(0));
}

The default implementation calls generator.apply(0)to get a zero-length array and then simply calls toArray(T[]). This goes through the Arrays.copyOf()fast path, so it's essentially the same speed as toArray(new T[0]).

默认实现调用generator.apply(0)获取零长度数组,然后简单地调用toArray(T[]). 这通过Arrays.copyOf()快速路径,因此它的速度基本上与toArray(new T[0]).



Note:- Just that the API use shall be guided along with a backward incompatibilitywhen used for code with nullvalues e.g. toArray(null)since these calls would now be ambiguous because of existing toArray(T[] a)and would fail to compile.

注意:- 只是当用于带有值的代码时,API 的使用应与向后不兼容一起进行指导,null例如,toArray(null)因为这些调用现在由于存在toArray(T[] a)而变得不明确并且将无法编译。

回答by Jagadeesh HN

For example, you have collection ArrayList with elements Student class:

例如,您有包含元素 Student 类的集合 ArrayList:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array

回答by Andrea Bergonzo

If you use Guava in your project you can use Iterables::toArray.

如果您在项目中使用 Guava,则可以使用Iterables::toArray.

Foo[] foos = Iterables.toArray(x, Foo.class);