将Java数组转换为可迭代

将Java数组转换为可迭代

本文介绍了将Java数组转换为可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个原语数组,例如int,int [] foo.可能不是一个小号.

I have an Array of primitives, for example for int, int[] foo. It might be a small sized one, or not.

int foo[] = {1,2,3,4,5,6,7,8,9,0};

从中创建Iterable<Integer>的最佳方法是什么?

What is the best way to create an Iterable<Integer> from it?

Iterable<Integer> fooBar = convert(foo);

注意:

请不要回答使用循环(除非您可以对编译器如何对它们做一些聪明的事情给出很好的解释?)

Please do not answer using loops (unless you can give a good explanation on how the compiler do something smart about them?)

还请注意

int a[] = {1,2,3};
List<Integer> l = Arrays.asList(a);

甚至不会编译

Type mismatch: cannot convert from List<int[]> to List<Integer>

也检查为什么数组不能分配给Iterable?在回答之前.

Also checkWhy is an array not assignable to Iterable?before answering.

此外,如果您使用某些库(例如Guava),请解释为什么这是最好的. (因为来自Google的答案不是完整的:P)

Also, if you use some library (e.g., Guava), please explain why this is the Best. ( Because its from Google is not a complete answer :P )

最后,由于似乎有作业,因此请避免发布作业代码.

Last, since there seems to be a homework about that, avoid posting homeworkish code.

推荐答案

Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);

尽管您需要使用Integer数组(而不是int数组)才能工作.

Though you need to use an Integer array (not an int array) for this to work.

对于基元,您可以使用番石榴:

For primitives, you can use guava:

Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
    <type>jar</type>
</dependency>

对于Java8 :(根据Jin Kwon的回答)

For Java8: (from Jin Kwon's answer)

final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();

这篇关于将Java数组转换为可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:18