{"id":18988,"date":"2022-01-25T18:42:26","date_gmt":"2022-01-25T13:12:26","guid":{"rendered":"https:\/\/java2blog.com\/?p=18988"},"modified":"2022-01-25T18:44:58","modified_gmt":"2022-01-25T13:14:58","slug":"java-arraylist-of-objects","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-arraylist-of-objects\/","title":{"rendered":"Create ArrayList of Objects in Java"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Using_the_add_method_to_create_ArrayList_of_objects_in_java\">Using the add() method to create ArrayList of objects in java<\/a><\/li><li><a href=\"#Using_parameterized_constructor_to_create_ArrayList_of_objects_in_java\">Using parameterized constructor to create ArrayList of objects in java<\/a><\/li><li><a href=\"#Using_addAll_method_to_create_ArrayList_of_objects_in_java\">Using addAll() method to create ArrayList of objects in java<\/a><\/li><li><a href=\"#Conclusion\">Conclusion<\/a><\/li><\/ul><\/div>\n<p>In this tutorial, we will learn how to create <a href=\"https:\/\/java2blog.com\/arraylist-in-java-with-example\/\" title=\"ArrayList\">ArrayList<\/a> of objects in Java. We will create a <code>Book<\/code> class with different properties and use it to create custom book objects when creating an <code>ArrayList<\/code> of objects.<\/p>\n<p>We will filter these book objects using certain criteria and add the book objects that meet the criteria in a new <code>ArrayList<\/code>.<\/p>\n<p>The following is the class declaration that we will use to instantiate our custom objects and the fields include <code>title<\/code>, <code>author<\/code>, <code>publisher<\/code>, and <code>bookPrice<\/code>.<\/p>\n<p>Create a book class with the properties and generate getter methods to retrieve their values when filtering. Generate a <code>toString()<\/code> method which will enable us to log the different values filtered to the console<\/p>\n<pre><code class=\"language-java\">package org.arpit.java2blog;\n\nimport java.math.BigDecimal;\nclass Book{\n    private String title;\n    private String author;\n    private String publisher;\n    private BigDecimal bookPrice;\n\n    public Book(String title,\n                String author,\n                String publisher,\n                BigDecimal bookPrice) {\n        this.title = title;\n        this.author = author;\n        this.publisher = publisher;\n        this.bookPrice = bookPrice;\n    }\n\n    public String getTitle() {\n        return title;\n    }\n\n    public String getAuthor() {\n        return author;\n    }\n\n    public String getPublisher() {\n        return publisher;\n    }\n\n    public Long getBookPrice() {\n        return Long.valueOf(String.valueOf(bookPrice));\n    }\n\n    @Override\n    public String toString() {\n        return &quot;Book{&quot; +\n                &quot;title=&#039;&quot; + title + &#039;\\&#039;&#039; +\n                &quot;, author=&#039;&quot; + author + &#039;\\&#039;&#039; +\n                &quot;, publisher=&#039;&quot; + publisher + &#039;\\&#039;&#039; +\n                &quot;, bookPrice=&quot; + bookPrice +\n                &#039;}&#039;;\n    }\n}<\/code><\/pre>\n<h3><span id=\"Using_the_add_method_to_create_ArrayList_of_objects_in_java\">Using the add() method to create ArrayList of objects in java<\/span><\/h3>\n<p>You can simply use <code>add()<\/code> method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.<br \/>\nHere is quick example:<\/p>\n<pre code=\"java\">\npackage org.arpit.java2blog;\n\nimport java.math.BigDecimal;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ArrayListListOfObjects {\n\n    public static void main(String[] args) {\n\n        \/\/ Declaring ArrayList\n        List<Book> listOfBooks =new ArrayList<>();\n\n        Book javaInAction = new Book(\"Java in action\", \"mary public\",\n                \"Everest publishers\", new BigDecimal(\"600\"));\n        Book introductionToJava =  new Book(\"Introduction to Java\", \"mary public\",\n                \"Heavyweight publishers\", new BigDecimal(\"100\"));\n        Book advancedDatabases =  new Book(\"Advanced databases\", \"charles darwin\",\n                 \"Longhorn publishers\", new BigDecimal(\"600\"));\n\n        \/\/ Adding objects to ArrayList\n        listOfBooks.add(javaInAction);\n        listOfBooks.add(introductionToJava);\n        listOfBooks.add(advancedDatabases);\n\n        \/\/ Printing the ArrayList\n        System.out.println(listOfBooks);\n    }\n}\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-green\">\n[Book{title=&#8217;Java in action&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Everest publishers&#8217;, bookPrice=600}, Book{title=&#8217;Introduction to Java&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Heavyweight publishers&#8217;, bookPrice=100}, Book{title=&#8217;Advanced databases&#8217;, author=&#8217;charles darwin&#8217;, publisher=&#8217;Longhorn publishers&#8217;, bookPrice=600}]\n<\/div>\n<p>Let&#8217;s take another example where we will <a href=\"https:\/\/java2blog.com\/java-8-stream-filter-examples\/\">filter<\/a> all the books authored by Mary and add the books to a new ArrayList using the <code>add()<\/code> method.<\/p>\n<p>We will use the <a href=\"https:\/\/java2blog.com\/java-8-stream\/\">Java 8 Stream<\/a> which provides us with an efficient way to filter our list of objects.<\/p>\n<pre><code class=\"language-java\">package org.arpit.java2blog;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class ArrayListOfObjects {\n    public static void main(String[] args) {\n         \/\/using add() method\n        System.out.println(&quot;Books authored by Mary: ================&quot;);\n        ArrayList&lt;Book&gt; booksForMary = new ArrayList&lt;&gt;();\n        List&lt;Book&gt; maryPublicBooks = books.stream()\n                .filter(book -&gt; book.getAuthor().equals(&quot;mary public&quot;))\n                .collect(Collectors.toList());\n        for (Book book : maryPublicBooks) {\n            booksForMary.add(book);\n        }\n        booksForMary.forEach(System.out::println);\n    }\n}<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-green\">\nBooks authored by Mary: ================<br \/>\nBook{title=&#8217;Java in action&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Everest publishers&#8217;, bookPrice=600}<br \/>\nBook{title=&#8217;Introduction to Java&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Heavyweight publishers&#8217;, bookPrice=100}\n<\/div>\n<section class=\"read-more-posts\">\n<div class=\"rm-header\">\n<h2>Further reading:<\/h2>\n<\/div>\n<div class=\"rm-wrap\">\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/initialize-arraylist-values-java\/\" target=\"_blank\" rel=\"noopener\">Initialize ArrayList with values in Java<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/initialize-arraylist-values-java\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/div>\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/print-arraylist-java\/\" target=\"_blank\" rel=\"noopener\">Print ArrayList in java<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/print-arraylist-java\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/p><\/div>\n<\/div>\n<\/section>\n<h3><span id=\"Using_parameterized_constructor_to_create_ArrayList_of_objects_in_java\">Using parameterized constructor to create ArrayList of objects in java<\/span><\/h3>\n<p>The <code>ArrayList<\/code> class has a constructor that accepts a collection of objects that we will initialize with book objects.<\/p>\n<p>Create a new ArrayList with custom book objects by passing a List containing our book objects to this ArrayList&#8217;s <a href=\"https:\/\/java2blog.com\/constructor-java\/\" title=\"constructor\">constructor<\/a>.<\/p>\n<p>Call the <a href=\"https:\/\/java2blog.com\/java-8-foreach-examples\/\" title=\"forEach()\">forEach()<\/a> method on the ArrayList created to print all the objects that were created during the ArrayList initialization.<\/p>\n<pre><code class=\"language-java\">package org.arpit.java2blog;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ArrayListOfObjects {\n    public static void main(String[] args) {\n        \/\/using parameterized constructor\n        ArrayList&lt;Book&gt; books = new ArrayList&lt;&gt;(List.of(\n                new Book(\n                        &quot;Java in action&quot;,\n                        &quot;mary public&quot;,\n                        &quot;Everest publishers&quot;,\n                        new BigDecimal(&quot;600&quot;)),\n                new Book(\n                        &quot;Introduction to Java&quot;,\n                        &quot;mary public&quot;,\n                        &quot;Heavyweight publishers&quot;,\n                        new BigDecimal(&quot;100&quot;)),\n                new Book(\n                        &quot;Advanced databases&quot;,\n                        &quot;charles darwin&quot;,\n                        &quot;Longhorn publishers&quot;,\n                        new BigDecimal(&quot;600&quot;))));\n\n        System.out.println(&quot;All books: ========================&quot;);\n        books.forEach(System.out::println);\n    }\n}<\/code><\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\nAll books: ========================<br \/>\nBook{title=&#8217;Java in action&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Everest publishers&#8217;, bookPrice=600}<br \/>\nBook{title=&#8217;Introduction to Java&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Heavyweight publishers&#8217;, bookPrice=100}<br \/>\nBook{title=&#8217;Advanced databases&#8217;, author=&#8217;charles darwin&#8217;, publisher=&#8217;Longhorn publishers&#8217;, bookPrice=600}\n<\/div>\n<p>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.<\/p>\n<h3><span id=\"Using_addAll_method_to_create_ArrayList_of_objects_in_java\">Using addAll() method to create ArrayList of objects in java<\/span><\/h3>\n<p>In this example, we will filter all the books where the price is greater than 100 and add the objects returned to a new <a href=\"https:\/\/java2blog.com\/arraylist-in-java-with-example\/\" title=\"ArrayList\">ArrayList<\/a> using the <code>addAll()<\/code> method.<\/p>\n<p>This method will return a list containing our filtered objects and we use the <code>forEach()<\/code> method to print the objects in the new ArrayList.<\/p>\n<pre><code class=\"language-java\">package com.Java2Blog;\n\nimport java.math.BigDecimal;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class ArrayListOfObjects {\n    public static void main(String[] args) {\n         \/\/using addAll() method\n        System.out.println(&quot;Books price &gt; 100: ================&quot;);\n        ArrayList&lt;Book&gt; expensiveBooks = new ArrayList&lt;&gt;();\n        List&lt;Book&gt; bookList = books.stream()\n                .filter(book -&gt; book.getBookPrice() &gt; 100)\n                .collect(Collectors.toList());\n        expensiveBooks.addAll(bookList);\n        expensiveBooks.forEach(System.out::println);\n    }\n}<\/code><\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\nBooks price &gt; 100: ================<br \/>\nBook{title=&#8217;Java in action&#8217;, author=&#8217;mary public&#8217;, publisher=&#8217;Everest publishers&#8217;, bookPrice=600}<br \/>\nBook{title=&#8217;Advanced databases&#8217;, author=&#8217;charles darwin&#8217;, publisher=&#8217;Longhorn publishers&#8217;, bookPrice=600}\n<\/div>\n<h3><span id=\"Conclusion\">Conclusion<\/span><\/h3>\n<p>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 <code>add()<\/code> method, and using the <code>addAll()<\/code> method.<\/p>\n<p>That&#8217;s all about how to create list of objects in java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsUsing the add() method to create ArrayList of objects in javaUsing parameterized constructor to create ArrayList of objects in javaUsing addAll() method to create ArrayList of objects in javaConclusion In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":19010,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[44,5],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18988"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=18988"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18988\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/19010"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=18988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=18988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=18988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}