$show=/label

Java ArrayList Real Time Examples

SHARE:

A quick guide to ArrayList api usage in java with real time examples.

1. Overview


In this tutorial, You'll learn ArrayList with Real-Time examples. If you are new to java programming, you'll get a question "What are the real-life examples of the ArrayList in Java?". Initial days when I was in engineering the second year, my professor was teaching ArrayList in java.

I have learned about it. ArrayList is a dynamic array to store the elements and also it grows the size automatically if it reaching its threshold value. But when we should be using the ArrayList in realtime applications.


Remember, for now, In the software world there is no application deployed in production without ArrayList. Now think about the usage of ArrayList. ArrayList can be used in many more scenarios in realtime.

We will be seeing a few real-time examples of ArrayList in Java.


Java ArrayList Real Time Examples


2. Collecting database records into ArrayList


JDBC is used to connect to the database and perform the operations on the tables. Every application needs to save user data and activities into the database. Once a Select query is executed, a ResultSet instance is returned. This ResultSet will contain all records.

For Example, the Amazon website has many customer's records in its database. If they want to retrieve the customers from the database and show it on a web screen. In this case, ArrayList will be used to add customer records from ResultSet.

Let us take a look at the below code.

Customer class:


package com.java.w3schools.blog.arraylist;

import java.io.Serializable;
import java.util.Date;

public class Customer implements Serializable {

 private String fullName;
 private String email;
 private String password;
 private String mobileNumber;
 private Date dateOfBirth;

 public String getFullName() {
  return fullName;
 }

 public void setFullName(String fullName) {
  this.fullName = fullName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getMobileNumber() {
  return mobileNumber;
 }

 public void setMobileNumber(String mobileNumber) {
  this.mobileNumber = mobileNumber;
 }

 public Date getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

}

Loading into ArrayList:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class SelectDataDemo {
    public static void main(String[] args) {
        Connection connection = null;
        Statement selectStmt = null;
  List customerList = new ArrayList;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:8080/AMAZONDB", "scoot", "tiger");
             
            selectStmt = connection.createStatement();
            ResultSet rs = selectStmt.executeQuery("SELECT FULL_NAME, EMAIL, PASSWORD, DOB, MOBILE_NUMBER FROM CUSTOMER ");
            while(rs.next())
            {
      Customer customer = new Customer();
      
               customer.setFullName(rs.getString(1)); 
               customer.setEmail(rs.getString(2)); 
               customer.setPassword(rs.getString(3)); 
               customer.setDateOfBirth(new java.util.Date(rs.getDate(4).getTime())); 
      customer.setMobileNumber(rs.getString(5)); 
      
      customerList.add(customer)
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                selectStmt.close();
                insertStmt.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  
  System.out.println("Customer records count : "+customerList.size());
    }
}

This is the best case to use the ArrayList to load the records. Every application must be having this kind of use case.

3. Returning List of transactions for Credit Card


Let us take a scenario where application A is using a third party API to get the credit card transactions. That API will returns all transactions for the recent month for a given credit card number.

Let us take a look at the response returned by API.

CreditCardResponse.java:

This class has instance variable transactions which are a type of List<Transaction>. This holds a list of all transactions and cardholder name, expiry date as well.

package com.java.w3schools.blog.arraylist;

import java.util.Date;
import java.util.List;

public class CreditCardResponse {
 private long cardNumber;
 private String nameOnCard;
 private Date expDate;
 private List transactions;
 public long getCardNumber() {
  return cardNumber;
 }
 public void setCardNumber(long cardNumber) {
  this.cardNumber = cardNumber;
 }
 public String getNameOnCard() {
  return nameOnCard;
 }
 public void setNameOnCard(String nameOnCard) {
  this.nameOnCard = nameOnCard;
 }
 public Date getExpDate() {
  return expDate;
 }
 public void setExpDate(Date expDate) {
  this.expDate = expDate;
 }
 public List getTransactions() {
  return transactions;
 }
 public void setTransactions(List transactions) {
  this.transactions = transactions;
 }
 
}

Transaction.java



package com.java.w3schools.blog.arraylist;

import java.util.Date;

public class Transaction {
 
 private long id;
 private Date processedDate;
 private double amount;
 private String description;
 public long getId() {
  return id;
 }
 public void setId(long id) {
  this.id = id;
 }
 public Date getProcessedDate() {
  return processedDate;
 }
 public void setProcessedDate(Date processedDate) {
  this.processedDate = processedDate;
 }
 public double getAmount() {
  return amount;
 }
 public void setAmount(double amount) {
  this.amount = amount;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
 
}

4. Use anywhere no removal and insertions in the middle


ArrayList is implemented on behavior to add the elements or values at the end of the list.
For example, if you are working with huge volume data and after adding the values to ArrayList if you do not want to remove the values or add new values in the between the exiting values then you are good to use the ArrayList in such scenario's.

5. Analyze the use case before using ArrayList


Before Blindly using the ArrayList, understand the scenario and data set. If no insertions and removals are then good to go with ArrayList.

PROCESS SEQUENTIALLY and ACTIONS VALIDATE, CONVERSOIONS, PROCESSING, POST VALIDATING?

Let us talk about another scenario. You have to process a file and it has 5 stages.

A) File reading
B) Validation
C) Conversion
D) PROCESSING
E) PostValidation

All these are the processes need to be run sequentially. First, add all of these processes to the ArrayList.

List steps = new ArrayList();

steps.add(FileReadingProcess.getInstance());
steps.add(ValidationProcess.getInstance());
steps.add(ConversionProcess.getInstance());
steps.add(ProcessingProcess.getInstance());
steps.add(PostValidationProcess.getInstance());

Now, pass the steps list to another service to follow the execution of the steps in order.


// invoking the service.
parsingService.sendStepsForFeed(steps, fileLocaion);
// apply all these phases to the file.


7. Conclusion

In this article, We've seen when and where to use ArrayList in real time applications. Explained real life scenarios such as adding the retrieved records from the database, adding credit card transactions.

And also discussed where not to use ArrayList and analyzing the input data to take the decision.

If you like the article please share it with friends. Post your questions to me.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java ArrayList Real Time Examples
Java ArrayList Real Time Examples
A quick guide to ArrayList api usage in java with real time examples.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVtDWrM5eVFHFWwK3XF3-J446f9sjADY5Q2O8wkj99ELX2xCaNMjKAbc-ZaPEpUGfMJOWFEhHDuhLjKJJ-VQvLOalT_sJQMW0PhORNK4TpzXPOIKwcRwnJafVkZ3L1vwE1lv6xH68_SJc/s320/Java+ArrayList+Real+Time+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVtDWrM5eVFHFWwK3XF3-J446f9sjADY5Q2O8wkj99ELX2xCaNMjKAbc-ZaPEpUGfMJOWFEhHDuhLjKJJ-VQvLOalT_sJQMW0PhORNK4TpzXPOIKwcRwnJafVkZ3L1vwE1lv6xH68_SJc/s72-c/Java+ArrayList+Real+Time+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/11/java-arraylist-real-time-examples.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/11/java-arraylist-real-time-examples.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content