Search code examples
javalambdatestngtestng-dataprovider

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.


Solution

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