Converting ArrayList to Array in java

前端 未结 10 1836
野的像风
野的像风 2020-12-04 18:44

I have an ArrayList with values like \"abcd#xyz\" and \"mnop#qrs\". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array a

相关标签:
10条回答
  • 2020-12-04 19:35
    List<String> list=new ArrayList<String>();
    list.add("sravan");
    list.add("vasu");
    list.add("raki"); 
    String names[]=list.toArray(new String[0]);
    

    if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

    0 讨论(0)
  • 2020-12-04 19:37

    This can be done using stream:

    List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
        List<String[]> objects = stringList.stream()
                                           .map(s -> s.split("#"))
                                           .collect(Collectors.toList());
    

    The return value would be arrays of split string. This avoids converting the arraylist to an array and performing the operation.

    0 讨论(0)
  • 2020-12-04 19:40

    This is the right answer you want and this solution i have run my self on netbeans

    ArrayList a=new ArrayList();
    a.add(1);
    a.add(3);
    a.add(4);
    a.add(5);
    a.add(8);
    a.add(12);
    
    int b[]= new int [6];
            Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
            m=(Integer[]) a.toArray(m);
    for(int i=0;i<a.size();i++)
    {
        b[i]=m[i]; 
        System.out.println(b[i]);
    }   
        System.out.println(a.size());
    
    0 讨论(0)
  • 2020-12-04 19:42
    import java.util.*;
    public class arrayList {
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            ArrayList<String > x=new ArrayList<>();
            //inserting element
            x.add(sc.next());
            x.add(sc.next());
            x.add(sc.next());
            x.add(sc.next());
            x.add(sc.next());
             //to show element
             System.out.println(x);
            //converting arraylist to stringarray
             String[]a=x.toArray(new String[x.size()]);
              for(String s:a)
               System.out.print(s+" ");
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题