Converting 'ArrayList to 'String[]' in Java

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

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

相关标签:
16条回答
  • 2020-11-22 02:52

    In Java 8, it can be done using

    String[] arrayFromList = fromlist.stream().toArray(String[]::new);
    
    0 讨论(0)
  • 2020-11-22 02:53
        List<String> 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<String []> allocateFunc = size -> { 
    return new String[size];
    };   
    String [] strArry= list.stream().toArray(allocateFunc);
    
    0 讨论(0)
  • 2020-11-22 02:54
    List<String> list = ..;
    String[] array = list.toArray(new String[0]);
    

    For example:

    List<String> list = new ArrayList<String>();
    //add some stuff
    list.add("android");
    list.add("apple");
    String[] stringArray = list.toArray(new String[0]);
    

    The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

    Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

    0 讨论(0)
  • 2020-11-22 02:54

    You can use the toArray() method for List:

    ArrayList<String> list = new ArrayList<String>();
    
    list.add("apple");
    list.add("banana");
    
    String[] array = list.toArray(new String[list.size()]);
    

    Or you can manually add the elements to an array:

    ArrayList<String> list = new ArrayList<String>();
    
    list.add("apple");
    list.add("banana");
    
    String[] array = new String[list.size()];
    
    for (int i = 0; i < list.size(); i++) {
        array[i] = list.get(i);
    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题