Java: how to convert HashMap to array

前端 未结 12 1951
时光取名叫无心
时光取名叫无心 2020-11-29 16:36

I need to convert a HashMap to an array; could anyone show me how it\'s done?

12条回答
  •  鱼传尺愫
    2020-11-29 17:04

    If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

    map.entrySet()
        .stream()
        .map(e -> new Object[]{e.getKey(), e.getValue()})
        .toArray(Object[][]::new);
    

    If your Objects are Strings and you need a String[][], try:

    map.entrySet()
        .stream()
        .map(e -> new String[]{e.getKey(), e.getValue().toString()})
        .toArray(String[][]::new);
    

提交回复
热议问题