Converting 'ArrayList to 'String[]' in Java

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

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

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

    In Java 8:

    String[] strings = list.parallelStream().toArray(String[]::new);
    
    0 讨论(0)
  • 2020-11-22 02:43

    Generics solution to covert any List<Type> to String []:

    public static  <T> String[] listToArray(List<T> list) {
        String [] array = new String[list.size()];
        for (int i = 0; i < array.length; i++)
            array[i] = list.get(i).toString();
        return array;
    }
    

    Note You must override toString() method.

    class Car {
      private String name;
      public Car(String name) {
        this.name = name;
      }
      public String toString() {
        return name;
      }
    }
    final List<Car> carList = new ArrayList<Car>();
    carList.add(new Car("BMW"))
    carList.add(new Car("Mercedes"))
    carList.add(new Car("Skoda"))
    final String[] carArray = listToArray(carList);
    
    0 讨论(0)
  • 2020-11-22 02:44

    You can use Iterator<String> to iterate the elements of the ArrayList<String>:

    ArrayList<String> list = new ArrayList<>();
    String[] array = new String[list.size()];
    int i = 0;
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
        array[i] = iterator.next();
    }
    

    Now you can retrive elements from String[] using any Loop.

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

    In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:

    List<String> list = List.of("one", "two", "three");
    String[] array = list.toArray(String[]::new)
    

    from java.base's java.util.Collection.toArray().

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

    An alternative in Java 8:

    String[] strings = list.stream().toArray(String[]::new);
    

    Java 11+:

    String[] strings = list.toArray(String[]::new);
    
    0 讨论(0)
  • 2020-11-22 02:50

    You can convert List to String array by using this method:

     Object[] stringlist=list.toArray();
    

    The complete example:

    ArrayList<String> list=new ArrayList<>();
        list.add("Abc");
        list.add("xyz");
    
        Object[] stringlist=list.toArray();
    
        for(int i = 0; i < stringlist.length ; i++)
        {
              Log.wtf("list data:",(String)stringlist[i]);
        }
    
    0 讨论(0)
提交回复
热议问题