Converting 'ArrayList to 'String[]' in Java

前端 未结 16 1785
情书的邮戳
情书的邮戳 2020-11-22 01:59

How might I convert an ArrayList object to a String[] array in Java?

16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 02:53

        List list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        String [] strArry= list.stream().toArray(size -> new String[size]);
    

    Per comments, I have added a paragraph to explain how the conversion works. First, List is converted to a String stream. Then it uses Stream.toArray to convert the elements in the stream to an Array. In the last statement above "size -> new String[size]" is actually an IntFunction function that allocates a String array with the size of the String stream. The statement is identical to

    IntFunction allocateFunc = size -> { 
    return new String[size];
    };   
    String [] strArry= list.stream().toArray(allocateFunc);
    

提交回复
热议问题