

We used an ArrayList constructor reference to provide an empty ArrayList to collect the elements.
#JAVA COLLECTIONS SINGLETONLIST CODE#
collect(Collectors.toCollection(ArrayList:: new)) Code language: Java ( java ) The toCollection() collects all Stream elements into the given List and returns it.

List list = Stream.of( 1, 2, 3).toList() Code language: Java ( java )Īlternatively, we can use toCollection() method of the Collectors class to provide a List instance. The toList() method returns a new List containing all Stream elements.Įxample of Stream toList() to create a new List containing Stream elements. The Stream interface offers the toList() method, which is an abstraction to collect the Stream elements in the form of an immutable Java List. Creating an ArrayList using Stream Collectors List list = new ArrayList(hashSet) Code language: Java ( java )įirst, we initialized a HashSet instance in Inline and used it in the ArrayList constructor.

The constructor creates a mutable instance of ArrayList containing all the elements from the given collection. List.add( 3) Code language: Java ( java ) Creating an ArrayList using a CollectionĪlternatively, we can initialize an ArrayList inline using another collection in the ArrayList constructor. Create an ArrayList using Another ArrayĪt the very basic, we can create an empty Java List using a constructor and add elements.Įxample of creating an empty Java List and adding elements to it.Creating an ArrayList using Arrays Class.Creating an Immutable ArrayList using Factory Methods.Create an Immutable ArrayList using Collections.Creating an ArrayList using Anonymous Subclass.Creating an ArrayList using Stream Collectors.Creating an ArrayList using a Collection.
