Can you initialize an ArrayList with values in Java?
Initialize ArrayList in JavaJava Java ArrayList Created: December-13, 2020 Show This tutorial discusses methods to initialize an ArrayList with values in one line in Java. It is handy for testing and minimalistic coding. Use Arrays.asList to Initialize an ArrayList in JavaIt is relatively easier to initialize a list instead of an ArrayList in Java with initial values in one line. However, if needed, it can be converted to an ArrayList. The below example illustrates both ways. Output: [Amsterdam, Paris, London] [Amsterdam, Paris, London]The only difference between the cities and cities_AL is that one is a List and the other is an ArrayList. Use new ArrayList() Initialize an ArrayList in JavaAnother method to initialize an ArrayList is using the new ArrayList() function. You can pre-assign all the values in a single line of code. Output: [Amsterdam, Paris, London]Use List.of() to Initialize an ArrayList in JavaIn Java9 or later, we can use the List.of() method instead of Arrays.asList() to initialize an ArrayList in Java. The below example illustrates this. import java.util.*; public class Main { public static void main(String[] args) { // Initialize a List ListOutput: Use Stream to Initialize an ArrayList in JavaWe can also use Stream to initialize an ArrayList in Java. The below example illustrates this. import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { ArrayListOutput: [Buenos Aires, Córdoba, La Plata]We have discussed several ways to initialize an ArrayList in Java in just one line with pre-assigning values in this article. Contribute DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page. Related Article - Java ArrayList
|