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

发布于 2024-09-11 04:15:07 字数 329 浏览 3 评论 0原文

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

UPD:(本节还有一个案例;如果您认为值得为其创建另一个线程,请留下评论):将 Collection 转换为 Bar[] 怎么样?其中 Bar 的构造函数有 1 个 Foo 类型的参数,即 public Bar(Foo foo){ ... }

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

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 Bar has constructor with 1 parameter of type Foo i.e. public Bar(Foo foo){ ... } ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

邮友 2024-09-18 04:15:07

其中 x 是集合:

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

Where x is the collection:

Foo[] foos = x.toArray(new Foo[x.size()]);
飘逸的'云 2024-09-18 04:15:07

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

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

Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);
假装爱人 2024-09-18 04:15:07

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

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

并进行转换,就像

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

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


这是我的更新建议:

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[]{});

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 toArray method will take the empty array to determine the correct type of the target array and create a new array for you.


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[]{});
且行且努力 2024-09-18 04:15:07

在 JDK/11 中,将 Collection 转换为 Foo[] 的另一种方法是使用 Collection.toArray(IntFunction生成器)如:

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

正如 @Stuart 所解释的邮件列表(强调我的),其性能本质上应该与现有的 Collection.toArray(new T[0]) 相同 --

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

它可以避免对新分配的数组进行零填充,因为它知道
整个数组内容将被覆盖。无论如何,这都是事实
公共 API 看起来像。

JDK 中 API 的实现如下:

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

默认实现调用generator.apply(0)来获取零长度数组
然后只需调用 toArray(T[]) 即可。这通过Arrays.copyOf()
快速路径,因此它的速度本质上与 toArray(new T[0]) 相同。


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

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:

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]) --

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.

The implementation of the API within the JDK reads:

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]).


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

南渊 2024-09-18 04:15:07

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

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

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

Foo[] foos = Iterables.toArray(x, Foo.class);
友欢 2024-09-18 04:15:07

这是更新部分中案例的最终解决方案(在 Google Collections 的帮助下):

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

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

Here's the final solution for the case in update section (with the help of 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 toArray method).

烟沫凡尘 2024-09-18 04:15:07

原文请参阅doublep答案:

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

作为对于更新:

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

For the original see doublep answer:

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);
}    
临风闻羌笛 2024-09-18 04:15:07

实际上在现代Java中,没有设置显式大小的版本更快。请参阅此答案:

.toArray(new MyClass[0]) 或 .toArray(new MyClass [myList.size()])?

这是由独立研究和 IntelliJ 团队支持的。

也就是说,这是当今最快的方法:

Foo[] foos = x.toArray(new Foo[0])

或者更好的是,具有一点安全性:

Foo[] foos = x == null ? null : x.toArray(new Foo[0])

Actually in modern Java, the version without setting the explicit size is faster. See this SO answer:

.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

This is backed up by independent research and the team at IntelliJ.

That is, this is the fastest approach today:

Foo[] foos = x.toArray(new Foo[0])

Or, even better, with a bit of safety:

Foo[] foos = x == null ? null : x.toArray(new Foo[0])
身边 2024-09-18 04:15:07

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

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

不顾 2024-09-18 04:15:07

例如,您有包含 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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文