简体   繁体   中英

Java Set to Object[][]

I have a Set<String> that I'd like to use for a TestNG parameterized test.

I want to go from <"a", "b", "c"> to {{"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.

You did everything right except the method reference to create the Object[][] . You're constructing a 2D-array with 1D-array elements holding the strings.

Change

Object[]::new

to

Object[][]::new

Once this is done, then you don't need the cast to Object[][] ; remove that as well.

All you need is Object[][]::new instead:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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