How To Create And Initialize List Or ArrayList In One Line In Java ...

Pages

  • Home
  • core java
  • spring
  • online courses
  • thread
  • java 8
  • coding
  • sql
  • books
  • oop
  • interview
  • certification
  • free resources
  • best
How to create and initialize List or ArrayList in one line in Java? Example creating and initializing List at the same time Sometimes we want to create and initialize a List like ArrayList or LinkedList in one line much like creating an array and initializing it on the same line. If you look at The array on Java programming language you can create and initialize both primitive and object arrays e.g. String array very easily in just one line but in order to create a List equivalent of that array, you need to type a lot of code. This is also one of the tricky Java question sometimes appears in Interview as Write Java code to create and initialize ArrayList in the same line.In this Java tips we will see this trick which allow you to create and initialize List much like an Array. This tip can also save a lot of time while creating a test program or quickly trying some stuff.

Java Tip to create and initialize List in one line

In our post 3 ways to convert Array to ArrayList in Java, we have discussed Arrays.asList() method. You can use Arrays.asList() method to create and initialize List at the same line. java.util.Arrays class act as a bridge between Array and List in Java and by using this method you can quickly create a List from Array, which looks like creating and initializing List in one line, as shown in the below program. package test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * * Java program to show * How to create and initialize a List in one line in Java * Arrays.asList() our go-to method to initialize List * in the same line. * * @author http://java67.blogspot.com */ public class ArrayListDemo{ public static void main(String args[]) { //You can create and initialize Array in just one line in Java String[] coolStringArray = new String[]{"Java" , "Scala" , "Groovy"}; System.out.println(" Array : " + Arrays.toString(coolStringArray)); //Now If you want to create // an ArrayList with three elements List<String> notSoCoolStringList = new ArrayList<String>(); notSoCoolStringList.add("Java"); notSoCoolStringList.add("Scala"); notSoCoolStringList.add("Groovy"); //It took four-line to create and initialize List System.err.println(" List : " + notSoCoolStringList); //Now here is simple Java tips to // create and initialize List in one line List<String> coolStringList = Arrays.asList("Java","Scala", "Groovy"); System.err.println(" List created and initialized at same line : " + coolStringList); } } Output: Array : [Java, Scala, Groovy] List : [Java, Scala, Groovy] List created and initialized at same line : [Java, Scala, Groovy] So this was our Java tip to create and initialize a List in the same line. Just remember that Arrays.asList() return java.util.List and not ArrayList or LinkedList. Another worth noting point is that List returned by Arrays.asList() is a fixed-length list that doesn't allow you to add or remove elements from it. add() and remove() method will throw UnSupportedOperationException if you try to add or remove elements from the List. Some programs mistook this List as a read-only List, which is not because it allows set() operation which can be used to change elements in the List. Only legitimate way to createread-only Collection is Collections.unmodifiableXXX() method.You can also see these Java Collections and Stream Courses to learn more about ArrayList and other collection classes in Java. How to create and initialize List or ArrayList in one line in Java? Example That's all on this Java tip about how to create and initialize a List in the same line in Java. This is a great tip that can save a lot of coding time if you frequently create and initialize a List with test data. You can use this trick to quickly create ArrayList with test data for your unit testing and demos. It really saves a lot of keystrokes in long run. Other Java Collection tutorials from java67 blog Difference between Vector and ArrayList in Java ConcurrentHashMap vs HashMap in Java HashMap vs Hashtable in Java Difference between TreeSet and TreeMap in Java How to sort ArrayList in Java

3 comments:

  1. HarinathJune 25, 2015 at 2:42 AM

    There is one correction required in your article. Calling remove() method on List returned from Arrays.asList() doesn't throw any UnSupportedOperationException but calling add() method will throw the exception.

    ReplyDeleteReplies
    1. AnonymousAugust 5, 2015 at 12:07 AM

      That's not true, even calling remove() method on List returned by Arrays.asList will throw UnsupportedException as seen below :Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:161) at java.util.AbstractList$Itr.remove(AbstractList.java:374) at java.util.AbstractCollection.remove(AbstractCollection.java:291)Only method which works without exception and modifies the list is set(index, value), which you can use to update the List.

      DeleteReplies
        Reply
    2. Reply
  2. AnitaApril 30, 2020 at 11:14 AM

    Cool!

    ReplyDeleteReplies
      Reply
Add commentLoad more...

Feel free to comment, ask questions if you have any doubt.

Newer Post Older Post Home Subscribe to: Post Comments (Atom)

Recommended Courses

  • best python courses
  • best java courses
  • system design courses
  • best spring courses
  • best hibernate courses
  • best design pattern courses
  • best Linux courses
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses

Array Tutorials

  • array - copy
  • array - tutorial
  • array - add/remove element
  • array - linked list
  • array - reverse
  • array - sorting
  • array - sum
  • array - binary search
  • array - vector
  • array - remove
  • array - reverse in place
  • array - to list
  • array - initialization
  • array - insertion sort
  • array - to string
  • array - example
  • array - data structure
  • array - compare
  • array - liner search

ArrayList Tutorials

  • arraylist - sort
  • arraylist - stream
  • arraylist - remove
  • arraylist - replace
  • arraylist - join
  • arraylist - size
  • arraylist - removeAll
  • arraylist - iterator
  • arraylist - to set
  • arraylist - hashmap
  • arraylist - sort descending
  • arraylist - guide
  • arraylist - with values
  • arraylist - concurrent modification
  • arraylist - to array
  • arraylist - first element
  • arraylist - reverse
  • arraylist - synchronized
  • arraylist - copyOnWriteArrayList

Categories

  • .NET
  • abstract class
  • ActiveMQ
  • Affiliate marketing
  • After Effects
  • Agentic AI
  • Agile
  • AI Tools
  • Amazon Web Service
  • android
  • Angular
  • Anonymous class
  • Ansible
  • apache camel
  • Apache kafka
  • Apache spark
  • app development
  • array
  • ArrayList
  • Artificial Intelligence
  • automation
  • aws
  • aws certification
  • Azure Certifications
  • backend development
  • bash
  • basics
  • beginners
  • best of java67
  • best practices
  • Big Data
  • binary tree
  • bit manipulation
  • black friday deals
  • Blockchain
  • BlockingDeque
  • books
  • Bootstrap
  • business analysis
  • ByteByteGo
  • C programming
  • C++
  • Career
  • ChatGPT
  • Chef
  • cloud certification
  • Cloud Computing
  • Code Example
  • Code Review
  • codecademy
  • Codemia
  • CodeRabbit
  • coding
  • coding exercise
  • Coding Interview
  • Coding Problems
  • Comparator
  • computer science
  • Computer Vision
  • concurrency tutorial
  • ConcurrentHashMap
  • core java
  • core java interview question answer
  • course review
  • Coursera
  • courses
  • crontab
  • CSS
  • Cyber Monday
  • Cyber Security
  • Data Analysis
  • data science
  • data structure and algorithm
  • Data Visualization
  • database
  • datacamp
  • date and time
  • debugging
  • deep learning
  • default methods
  • design pattern
  • DevOps
  • DevSecOps
  • Distributed Systems
  • Django
  • docker
  • double
  • Drawing
  • DSA
  • dyanmic programming
  • dynamic Programming
  • eBooks
  • Eclipse
  • EJB
  • enum
  • equals
  • error and exception
  • Ethical hacking
  • Excel
  • exception
  • Exponent
  • expressjs
  • FAANG
  • Figma
  • Firebase
  • flatmap
  • float
  • Flutter
  • free resources
  • freelancing
  • Frontend Masters
  • fun
  • Fundamental
  • fundamentals
  • Game development
  • garbage collection
  • general
  • Generics
  • gifts
  • git and github
  • golang
  • Google Cloud Certification
  • Google Cloud Platform
  • Gradle
  • grails
  • graph
  • graphic design
  • grep
  • Groovy
  • gRPC
  • Hadoop
  • HashMap
  • HashSet
  • haskell
  • Hibernate
  • Hibernate interview Question
  • homework
  • HTML
  • HTTP
  • HttpClient
  • i
  • interface
  • Internet of Things (IoT)
  • interview
  • interview questions
  • IT Certification
  • J2EE
  • Jackson
  • java
  • Java 5 tutorial
  • java 7
  • Java 8
  • java 9
  • java basics
  • Java Certification
  • Java collection tutorial
  • java concurrency tutorial
  • java design pattern
  • Java Enum
  • Java file tutorials
  • Java Functional Programming
  • Java Installation Guide
  • Java Interview Question
  • Java interview questions
  • Java IO interview question
  • java io tutorial
  • java map tutorials
  • java modules
  • Java Multithreading Tutorial
  • Java networking tutorial
  • Java Operator tutorial
  • Java programming Tutorial
  • Java String tutorial
  • Java7
  • JavaScript
  • JavaScript Interview Question
  • JavaScript Tutorial
  • JDBC
  • JEE Interview Questions
  • Jenkins
  • JMS
  • JPA
  • jQuery
  • JSON
  • JSP
  • JSP Interview Question
  • JSTL
  • JUnit
  • JVM
  • Keras
  • keystore
  • Kotlin
  • kubernetes
  • lambda expression
  • Laraval
  • learning
  • linked list
  • Linux
  • Log4j
  • logging
  • Lombok
  • LSAT
  • Mac OS X
  • machine learning
  • Mathematics
  • Matlab
  • Maven
  • MERN stack
  • Messaging
  • Microservices
  • Microsoft
  • Microsoft Azure Platform
  • Microsoft Excel
  • Microsoft Power BI
  • Mockito
  • MongoDB
  • MysQL
  • MySQL tutorial example
  • nested class
  • neural network
  • Next.js
  • NFT
  • NLP
  • Node.js
  • nslookup
  • object oriented programming
  • OCAJP
  • OCMJEA
  • OCPJP
  • offers
  • Oracle
  • Perl
  • personal development
  • Photoshop
  • PHP
  • pluralsight
  • PostgerSQL
  • postman
  • Powerpoint
  • programmers
  • programming
  • programming problems
  • Project Management
  • projects
  • Prompt Engineering
  • Proxy
  • Python
  • Pytorch
  • Quarkus
  • questions
  • Queue
  • R programming
  • RabbitMQ
  • React
  • React Hooks
  • react native
  • Record
  • Recursion
  • Redux
  • regular expression example
  • REST tutorials
  • Review
  • RoadMap
  • Ruby
  • Salesforce
  • SAT
  • Scala
  • Scala Interview Questions
  • Scalability
  • Scanner
  • scripting
  • Scrum
  • Scrum Master Certification
  • Selenium
  • SEO
  • Serialization
  • Servlet
  • Servlet Interview Questions
  • Set
  • shell scripting
  • smart contracts
  • Snowflake SnowPro Certification
  • soft link
  • soft skills
  • software architecture
  • Solaris
  • Solidity
  • Sorting Algorithm
  • Spark
  • spring boot
  • Spring Certification
  • spring cloud
  • spring data jpa
  • spring framework
  • spring interview question
  • spring mvc
  • spring security
  • sql
  • SQL interview Question
  • SQL Joins
  • SQL SERVER
  • ssl
  • Static
  • Statistics
  • Stream
  • String
  • Struts
  • Swift
  • swing
  • switch case
  • system design
  • System Design Interview Questions
  • Tableau
  • Tailwind
  • TensorFlow
  • ternary operator
  • testing
  • thread
  • thread interview questions
  • Time series analysis
  • Tips
  • tomcat
  • tools
  • tree
  • TreeMap
  • troubleshooting
  • TypeScript
  • Udacity
  • Udemy
  • UI and UX Design
  • UML
  • unit testing
  • Unity 3D
  • Unix
  • unreal engine
  • Video Editing
  • Vuejs
  • web design
  • web development
  • web scrapping
  • Web Service
  • Whizlabs
  • Wix
  • xml
  • YAML
  • ZTM Academy

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Search This Blog

Best Online Learning Resources and Platforms

  • Coursera Plus (40% OFF)
  • Datacamp Sale (50% OFF)
  • AlgoMonster Lifetime Plan (50% OFF)
  • Udemy Sale (80% OFF)
  • Baeldung (33% OFF)
  • LabEx Sale (50% OFF)
  • Codecademy Sale (60% OFF)
  • Udacity Sale (50% OFF)
  • ZTM Academy Sale (66% OFF)
  • Frontend Masters Deal
  • Whizlabs Deal (70% OFF)

Javarevisited

Loading...

Spring Interview Prep List

  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses

Subscribe for Discounts and Updates

Follow

Interview Questions

  • core java interview questions
  • SQL interview questions
  • data structure interview question
  • coding interview questions
  • java collection interview questions
  • java design pattern interview questions
  • thread interview questions
  • hibernate interview questions
  • j2ee interview questions
  • Spring Interview Questions
  • object oriented programming questions

Followers

Blog Archive

  • ▼  2025 (554)
    • ▼  July (71)
      • How to Convert a Comma Separated String to an Arr...
      • How to Show Open Save File Dialog in Java Swing Ap...
      • float and double data types in Java with Examples
      • Java - Convert String to Short Example
      • How to Fix Access restriction: The type BASE64Deco...
      • How to Fix javax.net.ssl.SSLHandshakeException: un...
      • 5 Difference between BufferedReader and Scanner cl...
      • 11 Examples of LocalDate, LocalTime, and LocalDate...
      • 3 Examples to Convert Date to LocalDate in Java 8?...
      • How to Convert Date to LocalDate in Java 8 - Examp...
      • How to convert String to Date in Java? Example Tut...
      • How to convert Date to LocalDateTime in Java 8 - E...
      • 10 Examples to DateTimeFormatter in Java 8 to Pars...
      • How to Format Date to String in Java 8 [Example Tu...
      • How to Convert java.util.Date to LocalDate in Java...
      • How to parse String to LocalDate in Java 8 - Date...
      • How to Convert String to LocalDateTime in Java 8 -...
      • How to Calculate Next Date and Year in Java? Local...
      • How to find difference between two dates in Java 8...
      • How to get current Day, Month, Year from Date in J...
      • How to convert Timestamp to Date in Java?JDBC Exam...
      • Difference between ServletConfig and ServletContex...
      • How to create and initialize List or ArrayList in ...
      • Difference between include directive, include acti...
      • Difference between UNION vs UNION ALL in SQL? Example
      • Can you join two unrelated tables in SQL? Cross Jo...
      • Difference between Primary key vs Candidate Key in...
      • Difference between Clustered and Non-Clustered Ind...
      • Difference between Primary key vs Unique key in SQ...
      • Where Is Python Used In The Real World?
      • Top 10 tools for SQL Developers and Database Admin...
      • Top 5 advanced JavaScript function concepts to Learn
      • Top 7 Gift Ideas for Programmers, Coders, and Soft...
      • Top 20 UI and UX Design Interview Questions and An...
      • Top 21 Chef Interview Questions and Answers for De...
      • Top 20 Shell Scripting Interview Questions and Ans...
      • Top 20 Bootstrap Interview Questions Answers for W...
      • Top 20 Artificial Intelligence Interview Questions...
      • Top 20 Golang Interview Questions with Answers
      • Top 20 Hadoop Interview Questions and Answers for ...
      • Top 20 Google Cloud Interview Questions with Answers
      • Top 20 Kubernetes Interview Questions Answers for ...
      • Top 27 Dynamic Programming Interview Questions for...
      • Top 20 Unity Interview Questions and Answers for G...
      • Top 20 Unreal Engine Interview Question and Answer...
      • Top 20 TypeScript Interview Questions and Answers ...
      • Top 5 Udemy Courses to Learn Distributed Systems i...
      • Is System Design Interview Inside Guide Vol 1 and ...
      • 10 Best System Design Interview Courses for Softwa...
      • Top 15 Courses to Learn System Design and Software...
      • Review - Is AlgoMonster Good Resource For Coding I...
      • Top 8 Online Courses to Learn System Design and So...
      • 70+ Coding Interview Questions for Software Engine...
      • Difference between Daemon Thread vs User Thread in...
      • How to join two threads in Java? Thread.join() exa...
      • How to stop a thread in Java? Example
      • 10 Things about Threads Every Java Programmer Shou...
      • Difference between int and Integer Types in Java? ...
      • What is Thread and Runnable in Java? Example
      • What is blank final variable in Java - Example
      • Access Modifiers in Java - Public, Private, Protec...
      • How to display date in multiple timezone in Java w...
      • JDBC - How to Convert java.sql.Date to java.util.D...
      • 5 Essential JDK 7 Features for Java Programmers
      • Difference between DOM vs SAX Parser in Java - XML...
      • How to configure Daily Log File Rolling in Java us...
      • Eclipse and NetBeans Keyboard Shortcuts for Java P...
      • How to convert int value to a Long object in Java?...
      • How to Create Random Alphabetic or AlphaNumeric St...
      • How to Order and Sort Objects in Java? Comparator ...
      • Difference between int and Integer data type in Ja...

Privacy

  • Privacy Policy
  • Terms & Conditions

Popular Posts

  • 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
  • How to fix "illegal start of expression" error in Java? Example
  • 5 Examples of Formatting Float or Double Numbers to String in Java
  • Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
  • Top 10 Frequently asked SQL Query Interview Questions Answers

Subscribe

Get new posts by email:
Subscribe

Tag » How To Initialize A List In Java