Java 创建具有重复元素的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26299612/
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
Creating a list with repeating element
提问by laurt
Is there an utility method in Java that generates a list or array of a specified length with all elements equal to a specified value (e.g ["foo", "foo", "foo", "foo", "foo"])?
Java 中是否有实用方法可以生成指定长度的列表或数组,其中所有元素都等于指定值(例如 ["foo", "foo", "foo", "foo", "foo"])?
采纳答案by arshajii
You can use Collections.nCopies
. Note that this copies the referenceto the given object, not the object itself. If you're working with strings, it won't matter because they're immutable anyway.
您可以使用Collections.nCopies
. 请注意,这会复制对给定对象的引用,而不是对象本身。如果您正在处理字符串,那没关系,因为它们无论如何都是不可变的。
List<String> list = Collections.nCopies(5, "foo");
System.out.println(list);
[foo, foo, foo, foo, foo]
回答by René Link
For an array you can use Arrays.fill(Object[] a, Object val)
对于数组,您可以使用Arrays.fill(Object[] a, Object val)
String[] strArray = new String[10];
Arrays.fill(strArray, "foo");
and if you need a list, just use
如果你需要一个列表,只需使用
List<String> asList = Arrays.asList(strArray);
Then I have to use two lines: String[] strArray = new String[5]; Arrays.fill(strArray, "foo");. Is there a one-line solution?
然后我必须使用两行: String[] strArray = new String[5]; Arrays.fill(strArray, "foo");。有单线解决方案吗?
You can use Collections.nCopies(5, "foo")as a one-line solution to get a list :
您可以使用Collections.nCopies(5, "foo")作为单行解决方案来获取列表:
List<String> strArray = Collections.nCopies(5, "foo");
or combine it with toArray
to get an array.
或者将它与它结合起来toArray
得到一个数组。
String[] strArray = Collections.nCopies(5, "foo").toArray(new String[5]);
回答by maxpovver
Version you can use for primitive arrays(Java 8):
可用于原始数组的版本(Java 8):
DoubleStream.generate(() -> 123.42).limit(777).toArray(); // returns array of 777 123.42 double vals
Note that it returns double[]
, not Double[]
请注意,它返回double[]
,而不是Double[]
Works for IntegerStream, DoubleStream, LongStream
适用于 IntegerStream、DoubleStream、LongStream