Array to Collection: Optimized code

前端 未结 10 2012
萌比男神i
萌比男神i 2021-01-31 14:26

Is there a better way of achieving this?

public static List toList(String[] array) {

    List list = new ArrayList(array.length);

          


        
相关标签:
10条回答
  • 2021-01-31 15:03
    Arrays.asList(array);    
    

    Example:

     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
    

    See Arrays.asList class documentation.

    0 讨论(0)
  • 2021-01-31 15:03

    Based on the reference of java.util.Collections.addAll(Collection<? super String> c, String... elements) its implementation is similar to your first method, it says

    Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

    Its implementation in jdk is (jdk7)

    public static <T> boolean addAll(Collection<? super T> c, T... elements) {
        boolean result = false;
        for (T element : elements)
            result |= c.add(element);
        return result;
    }
    

    So among your samples the better approach must be Collections.addAll(list, array);

    Since Java 8, we can use Stream api which may perform better

    Eg:-

    String[] array = {"item1", "item2", "item3"};
    
    Stream<String> stream = Stream.of(array);
    
    //if the array is extremely large 
    stream = stream.parallel();
    
    final List<String> list = stream.collect(Collectors.toList());
    

    If the array is very large we can do it as a batch operation in parallel using parallel stream (stream = stream.parallel()) that will utilize all CPUs to finish the task quickly. If the array length is very small parallel stream will take more time than sequential stream.

    0 讨论(0)
  • 2021-01-31 15:05

    Another way to do it:

    Collections.addAll(collectionInstance,array);
    
    0 讨论(0)
  • 2021-01-31 15:06
    Arrays.asList(array)
    

    Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

    In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

    Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

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