将地图转换为数组 Java

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>());
              }
            map.get(token[1]).add(element);
        }
        System.out.println(map);

        return map;
    }

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

我正在为某些匹配的测试用例构建测试套件。现在我想将它转换为一个数组,因为我正在从它构造一个 dynamicTest:

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


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

有什么方法可以将它转换成像Object[String][Tuple4]

这样的数组吗

编辑:

好的,现在我有了这段代码:

`@TestFactory public 流 dynamicTuple4TestsFromStream() 抛出 IOException{ 初始化();

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

            }

        })); }`

我得到了这个例外: incompatible types: void cannot be converted to java.util.stream.Stream<org.junit.jupiter.api.DynamicTest>

How/Why?

虽然您可以相当轻松地编写代码将您的地图转换为数组,但您实际上并不需要为了获得一系列测试。

您只需要获取 Map.Entry<String,List<Tuple>> 流并将其展平为 Map.Entry<String,Tuple>

例如:

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

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

...打印...

Greeting Hello
Greeting World
Farewell Goodbye
Farewell Suckers

当然如果你真的想要一个数组,你可以改变映射:

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

... 并将生成的数组流收集到数组数组中。但我不明白这一点。

(这将受益于功能分解重构,但它说明了这一点)