Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, November 6, 2019

Java ArrayList 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.



No comments:

Post a Comment

Please do not add any spam links in the comments section.