简体   繁体   English

Java设置为Object [] []

[英]Java Set to Object[][]

I have a Set<String> that I'd like to use for a TestNG parameterized test. 我有一个Set<String> ,我想将其用于TestNG参数化测试。

I want to go from <"a", "b", "c"> to {{"a"}, {"b"}, {"c"}} 我想从<"a", "b", "c">转到{{"a"}, {"b"}, {"c"}}

I've tried: 我试过了:

Set<String> elements = Stream.of("a", "b", "c").collect(Collectors.toSet());

Object[][] elementsArray = (Object[][]) elements.stream()
                .map(t -> new Object[] {t})
                .toArray(Object[]::new);

but it doesn't work. 但这不起作用。 Any pointers on how to achieve this? 关于如何实现这一目标的任何指针? Non-lambda solutions are welcome as well. 也欢迎非lambda解决方案。

You did everything right except the method reference to create the Object[][] . 除了创建Object[][]的方法引用之外,您所做的一切都正确。 You're constructing a 2D-array with 1D-array elements holding the strings. 您正在使用包含字符串的1D数组元素构造2D数组。

Change 更改

Object[]::new

to

Object[][]::new

Once this is done, then you don't need the cast to Object[][] ; 一旦完成,就不需要强制转换为Object[][] remove that as well. 也将其删除。

All you need is Object[][]::new instead: 您只需要Object[][]::new

Set<String> elements = Stream.of("a", "b", "c").collect(Collectors.toSet());

Object[][] elementsArray = elements.stream()
                .map(t -> new Object[] {t})
                .toArray(Object[][]::new);

With Object[]::new you're creating an Object[] and then casting it to an Object[][] (which will fail). 使用Object[]::new您可以创建Object[] ,然后将其强制转换为Object[][] (这将失败)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM