Hendrik Hendrik -4 years ago 276
Java Question

Convert Map to Array Java

public Map<String, List<Tuple4>> buildTestcases(ArrayList<Tuple4> list){
Map<String, List<Tuple4>> map = new LinkedHashMap<String, List<Tuple4>>();

for(Tuple4 element: list){

String[] token = element.c.split("\\s");

if (!map.containsKey(token[1])) {
map.put(token[1], new ArrayList<Tuple4>());

return map;

public Tuple4(String a, String b, String c, String d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;

I am constructing a Testsuite for certain matching Testcases. Now I want to convert it to an Array since I'm constructing a dynamicTest from it:

return Stream.of(<Array needed>).map(

tuple -> DynamicTest.dynamicTest("Testcase: ", () -> { ... }

Is there any way to convert it to an Array like


Okay, now I have this piece of code:

public Stream dynamicTuple4TestsFromStream() throws IOException{

return map.entrySet().stream()
.flatMap(entry ->
.map(s -> new AbstractMap.SimpleEntry<>(entry.getKey(), s)))
.forEach(e -> DynamicTest.dynamicTest("Testcase: " +e.getKey(), () -> {
tester = new XQueryTester(e.getValue().a, e.getValue().b);


})); }`

and im getting this exception:
incompatible types: void cannot be converted to java.util.stream.Stream<org.junit.jupiter.api.DynamicTest>


Answer Source

While you could fairly easily write code to transform your map into an array, you don't really need to in order to get a stream of tests.

You just need get stream of Map.Entry<String,List<Tuple>> and flatten it into a stream of Map.Entry<String,Tuple>

For example:

    Map<String, List<String>> map = new HashMap<>();
    map.put("Greeting", Arrays.asList("Hello", "World"));
    map.put("Farewell", Arrays.asList("Goodbye", "Suckers"));

            .flatMap(entry -> 
                            .map(s -> new AbstractMap.SimpleEntry<>(entry.getKey(), s)))
            .forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));

... prints ...

Greeting Hello
Greeting World
Farewell Goodbye
Farewell Suckers

Of course if you really want an array, you can change the mapping:

 .flatMap(entry -> entry.getValue().stream()
       .map( s -> new Object[] { entry.getKey(), entry.getValue() })

... and collect the resulting stream of arrays into an array-of-arrays. But I don't see the point.

(This would benefit from a functional-decomposition refactor, but it illustrates the point)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download