$show=/label

Java ArrayList Real Time Examples

SHARE:

1. Overview In this tutorial, You'll learn ArrayList with Real-Time examples . If you are new to java programming, you'll get a ...

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,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,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,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java ArrayList Real Time Examples
Java ArrayList Real Time Examples
https://1.bp.blogspot.com/-o2T3ZopJbRk/XcMJ-QQMbMI/AAAAAAAAB4Q/AWqpZ0rHp8w1DJ9E-pXMow9pYtTeqlywgCLcBGAsYHQ/s320/Java%2BArrayList%2BReal%2BTime%2BExamples.png
https://1.bp.blogspot.com/-o2T3ZopJbRk/XcMJ-QQMbMI/AAAAAAAAB4Q/AWqpZ0rHp8w1DJ9E-pXMow9pYtTeqlywgCLcBGAsYHQ/s72-c/Java%2BArrayList%2BReal%2BTime%2BExamples.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