将 Java 数组转换为可迭代的 [英] Convert Java Array to Iterable
问题描述
我有一个原始数组,例如 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
的最佳方法是什么?
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?在回答之前.
此外,如果您使用某个库(例如 Guava),请解释为什么这是最好的.(因为它来自谷歌不是一个完整的答案: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>
对于带有 lambdas 的 Java8:(灵感来自 Jin Kwon 的回答)
For Java8 with lambdas: (Inspired by Jin Kwon's answer)
final int[] arr = { 1, 2, 3 };
final Iterable<Integer> i1 = () -> Arrays.stream(arr).iterator();
final Iterable<Integer> i2 = () -> IntStream.of(arr).iterator();
final Iterable<Integer> i3 = () -> IntStream.of(arr).boxed().iterator();
这篇关于将 Java 数组转换为可迭代的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!