Create ArrayList from array

后端 未结 30 1866
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this

30条回答
  •  遥遥无期
    2020-11-21 23:05

    Given Object Array:

    Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};
    

    Convert Array to List:

        List list = Arrays.stream(array).collect(Collectors.toList());
    

    Convert Array to ArrayList

        ArrayList arrayList = Arrays.stream(array)
                                           .collect(Collectors.toCollection(ArrayList::new));
    

    Convert Array to LinkedList

        LinkedList linkedList = Arrays.stream(array)
                         .collect(Collectors.toCollection(LinkedList::new));
    

    Print List:

        list.forEach(element -> {
            System.out.println(element.i);
        });
    

    OUTPUT

    1

    2

    3

提交回复
热议问题