Create ArrayList of Objects in Java

Java ArrayList of objects

In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and use it to create custom book objects when creating an ArrayList of objects.

We will filter these book objects using certain criteria and add the book objects that meet the criteria in a new ArrayList.

The following is the class declaration that we will use to instantiate our custom objects and the fields include title, author, publisher, and bookPrice.

Create a book class with the properties and generate getter methods to retrieve their values when filtering. Generate a toString() method which will enable us to log the different values filtered to the console

Using the add() method to create ArrayList of objects in java

You can simply use add() method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.
Here is quick example:

Output:

[Book{title=’Java in action’, author=’mary public’, publisher=’Everest publishers’, bookPrice=600}, Book{title=’Introduction to Java’, author=’mary public’, publisher=’Heavyweight publishers’, bookPrice=100}, Book{title=’Advanced databases’, author=’charles darwin’, publisher=’Longhorn publishers’, bookPrice=600}]

Let’s take another example where we will filter all the books authored by Mary and add the books to a new ArrayList using the add() method.

We will use the Java 8 Stream which provides us with an efficient way to filter our list of objects.

Output:

Books authored by Mary: ================
Book{title=’Java in action’, author=’mary public’, publisher=’Everest publishers’, bookPrice=600}
Book{title=’Introduction to Java’, author=’mary public’, publisher=’Heavyweight publishers’, bookPrice=100}

Using parameterized constructor to create ArrayList of objects in java

The ArrayList class has a constructor that accepts a collection of objects that we will initialize with book objects.

Create a new ArrayList with custom book objects by passing a List containing our book objects to this ArrayList’s constructor.

Call the forEach() method on the ArrayList created to print all the objects that were created during the ArrayList initialization.

Output:

All books: ========================
Book{title=’Java in action’, author=’mary public’, publisher=’Everest publishers’, bookPrice=600}
Book{title=’Introduction to Java’, author=’mary public’, publisher=’Heavyweight publishers’, bookPrice=100}
Book{title=’Advanced databases’, author=’charles darwin’, publisher=’Longhorn publishers’, bookPrice=600}

For the next examples, we will use this list of books to create a new ArrayList of objects by filtering this list and adding the filtered objects to the new list.

Using addAll() method to create ArrayList of objects in java

In this example, we will filter all the books where the price is greater than 100 and add the objects returned to a new ArrayList using the addAll() method.

This method will return a list containing our filtered objects and we use the forEach() method to print the objects in the new ArrayList.

Output:

Books price > 100: ================
Book{title=’Java in action’, author=’mary public’, publisher=’Everest publishers’, bookPrice=600}
Book{title=’Advanced databases’, author=’charles darwin’, publisher=’Longhorn publishers’, bookPrice=600}

Conclusion

In this tutorial, we have learned how to create an ArrayList of objects by using the following approaches: using parameterized constructor during ArrayList initialization, using the add() method, and using the addAll() method.

That’s all about how to create list of objects in java.


import_contacts

You may also like:

Related Posts

  • 17 May

    How to Add Multiple Values for Single Key In HashMap in Java

    Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

  • 10 September

    How to remove element from Arraylist in java while iterating

    Table of ContentsIntroductionUsing Collection’s removeIf() methodUsing ListIterator classUsing removeAll() methodUsing Java 8 Stream to filter List itemsConclusion Introduction In this tutorial, you will learn how to remove element from Arraylist in java while iterating using different implementations provided by Java. It is necessary to understand the right way to remove items from a List because […]

  • Print HashMap in java
    30 June

    Print HashMap in Java

    Table of ContentsPrint from the HashMap ReferencePrint HashMap using foreach method with keyset()Print HashMap using Consumer with entrySet()Print HashMap using Arrays’s asList() methodPrint HashMap using Collections’s singletonList()Print HashMap using getkey() and getValue with entrySet()Print HashMap using BiConsumerPrint HashMap using IteratorPrint HashMap using custom ObjectsConclusion In this article, we will see how to print HashMap in […]

  • Print LinkedList in java
    26 June

    Print LinkedList in java

    Table of ContentsJava inbuilt LinkedListPrint LinkedList using a for loopPrint LinkedList using Enhanced for loopPrint LinkedList using streamsPrint LinkedList using toString() methodPrint LinkedList using IteratorPrint LinkedList using custom objectsCustom singly LinkedListHow to print a custom singly LinkedListConclusion Java inbuilt LinkedList Java inbuilt LinkedList class uses doubly linked list as internal data structure to store its […]

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.