Converting String array to java.util.List

前端 未结 6 1826
孤街浪徒
孤街浪徒 2020-12-07 11:30

How do I convert a String array to a java.util.List?

相关标签:
6条回答
  • 2020-12-07 11:58
    import java.util.Collections;
    
    List myList = new ArrayList();
    String[] myArray = new String[] {"Java", "Util", "List"};
    
    Collections.addAll(myList, myArray);
    
    0 讨论(0)
  • 2020-12-07 12:10

    Use the static List list = Arrays.asList(stringArray) or you could just iterate over the array and add the strings to the list.

    0 讨论(0)
  • 2020-12-07 12:13

    The Simplest approach:

    String[] stringArray = {"Hey", "Hi", "Hello"};
    
    List<String> list = Arrays.asList(stringArray);
    
    0 讨论(0)
  • 2020-12-07 12:17
    List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});
    

    This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

    If you want a modifiable a List:

    List<String> strings = 
         new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));
    

    This will copy all elements from the source array into a new list (complexity: O(n))

    0 讨论(0)
  • 2020-12-07 12:18

    First Step you need to create a list instance through Arrays.asList();

    String[] args = new String[]{"one","two","three"};
    List<String> list = Arrays.asList(args);//it converts to immutable list
    

    Then you need to pass 'list' instance to new ArrayList();

    List<String> newList=new ArrayList<>(list);
    
    0 讨论(0)
  • 2020-12-07 12:18

    On Java 14 you can do this

    List<String> strings = Arrays.asList("one", "two", "three");
    
    0 讨论(0)
提交回复
热议问题