Array to a list method

1, manually implement

Traversing the array are read and stored to a List

    public List<String> toListTest1(String[] array){
        List<String> list = new ArrayList<>(array.length);
        for (String t : array) {
            list.add(t);
        }
        return list;
    }

2, using the method within the class asList Arrays ()

Let me Arrays.asList (), methods, arrays into List, however, the return value is just an object Arrays, if .add () .remove () method will java.lang.UnsupportedOperationException error, because java.util. Arrays just inside a class, and no override these methods;

    public List<String> toListTest2(String[] array){
        List<String> list = new ArrayList<>(Arrays.asList(this.strings));
        return list;
    }

3, using the stream Arrays

    public List<String> toListTest3(String[] array){
        List<String> list = Arrays.stream(array).collect(Collectors.toList());
        return list;
    }

There are usage restrictions, in order to use more than 1.8

There are many ways: CollectionUtils.addAll (), etc.

Guess you like

Origin www.cnblogs.com/lcxz/p/11249945.html