使用重复元素创建列表


82

Java中是否有一种实用程序方法可以生成具有指定长度的列表或数组,且所有元素都等于指定值(例如[“ foo”,“ foo”,“ foo”,“ foo”,“ foo”])?

Answers:


144

您可以使用Collections.nCopies。请注意,这会将引用复制到给定的对象,而不是对象本身。如果您使用的是字符串,则没关系,因为它们始终是不可变的。

List<String> list = Collections.nCopies(5, "foo");
System.out.println(list);
[foo,foo,foo,foo,foo]

20

对于数组,可以使用Arrays.fill(Object [] a,Object val)

String[] strArray = new String[10];
Arrays.fill(strArray, "foo");

如果您需要列表,请使用

List<String> asList = Arrays.asList(strArray);

然后,我必须使用两行:String [] strArray = new String [5]; Arrays.fill(strArray,“ foo”);。有单线解决方案吗?

您可以使用Collections.nCopies(5,“ foo”)作为单行解决方案来获取列表:

List<String> strArray = Collections.nCopies(5, "foo");

或与之结合toArray以获得数组。

String[] strArray = Collections.nCopies(5, "foo").toArray(new String[5]);

1
然后,我必须使用两行:String[] strArray = new String[5]; Arrays.fill(strArray, "foo");。有单线解决方案吗?
2014年

很简单:Collections.nCopies(5,“ foo”)谢谢!
MarceloRebouças17年

4

可用于原始数组的版本(Java 8):

DoubleStream.generate(() -> 123.42).limit(777).toArray(); // returns array of 777 123.42 double vals

请注意,它返回double[],而不是Double[]

适用于IntegerStream,DoubleStream,LongStream


1

使用IntStream,您可以生成一定范围的整数,将它们映射到所需的元素并将其作为列表收集。

List<String> list = IntStream.rangeClosed(0, 5)
            .mapToObj(i -> "foo")
            .collect(Collectors.toList());

或者,作为数组

 String[] arr = IntStream.rangeClosed(0, 5)
            .mapToObj(i -> "foo")
            .toArray(String[]::new);

1

如果您的对象不是不可变的或不是参考透明的,则可以使用

Stream.generate(YourClass::new).limit(<count>)

并收集到列表中

.collect(Collectors.toList())

或排列

.toArray(YourClass[]::new)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.