Skip to main content

Java ArrayList Common Program Examples

Java ArrayList Common Program Examples

In this article, we are going to learn common programs related to Java ArrayList that help in our day-to-day programming activities. ArrayList is a very important class in Java and used extensively in our programs. Therefore, it is good to learn common tasks related to ArrayList so that we can solve easily our day-to-day programming challenges around the ArrayList.
If you are new to ArrayList and want to learn the basics of ArrayList, I suggest you read this article first: All about ArrayList in Java. Now, let's look at the common programs related to ArrayList.

Content of the Article


How to initialize ArrayList in Java?

To use an ArrayList in our program, we must know how we can initialize ArrayList in Java. Look at the example which creates and initialize an ArrayList to store the name of a few programming languages.

Java ArrayList Example 1: Initialize ArrayList in Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                        Arrays.asList("Java", "C++", "Python", "NodeJS", "JavaScript"));
                System.out.println("Language ArrayList : " + languageList);
        }
}
Output
Language ArrayList : [Java, C++, Python, NodeJS, JavaScript]

If this example is not enough to you. You can read this article, if you want to learn different ways to initialize ArrayList in Java.

How to iterate ArrayList in Java?

ArrayList provides a method called iterator() which returns an object of Iterator. Iterator is an interface defined in java.util package and the implementation of Iterator is provided by the ArrayList internally.
Here is an example to iterate list of book names using iterator.

Java ArrayList Example 2: Iterate ArrayList in Java

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> bookList = new ArrayList<>();
                bookList.add("Programming In Java");
                bookList.add("Introduction to Algorithms");
                bookList.add("Data Structures");
                bookList.add("Learn C++");
                bookList.add("Computer Networks");

                Iterator<String> iterator = bookList.iterator();

                while (iterator.hasNext()) {
                        String nextElement = iterator.next();
                        System.out.println(nextElement);
                }
        }
}
Output
Programming In Java
Introduction to Algorithms
Data Structures
Learn C++
Computer Networks

There are exists so many methods to iterate an ArrayList. I have explained a few of them in this post: How to iterate ArrayList in Java.

How to convert ArrayList to Array in Java?

ArrayList provides a method named as toArray() which is used to turn an ArrayList to Array in Java. This method takes an argument of an empty array whose size must be greater-than or equal-to the size of ArrayList and put all the elements from arraylist to array in java. If the array size is smaller than the arraylist then a new array is created and returned with all the elements of the ArrayList.

Java ArrayList Example 3: Convert ArrayList to Array Using toArray() method

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languages = new ArrayList<>(
                        Arrays.asList("Java", "C++", "Python", ".net", "PHP"));

                String[] languageArray = convertArrayListToArray(languages);
                for (String language : languageArray) {
                        System.out.println(language);
                }
        }

        private static String[] convertArrayListToArray(ArrayList<String> arrayList) {
                String[] array = new String[arrayList.size()];
                arrayList.toArray(array);
                return array;
        }
}
Output
Java
C++
Python
.net
PHP

Here, you can read the full article on common methods to convert ArrayList to Array.

How to convert ArrayList to HashMap in Java?

We regularly come across the instances to transform an ArrayList into a HashMap, so it's very important to learn how to convert an ArrayList into a HashMap. Here is an example of ArrayList to HashMap.

Java ArrayList Example 4: ArrayList to HashMap in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                                Arrays.asList("Java", "C++", "Python", "PHP" , "NodeJS"));
                System.out.println("-------------ArrayList---------------");
                for (String language : languageList) {
                        System.out.println(language);
                }
                System.out.println("--------------HashMap----------------");
                HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList);
                for(Map.Entry<String, Integer> entry : languageMap.entrySet()) {
                        System.out.println(entry.getKey() + " : " + entry.getValue());
                }
        }

        private static HashMap<String, Integer> convertArrayListToHashMap(
            ArrayList<String> arrayList) {
                HashMap<String, Integer> hashMap = new HashMap<>();
                for (String str : arrayList) {
                        hashMap.put(str, str.length());
                }
                return hashMap;
        }
}
Output
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
PHP : 3
NodeJS : 6
Python : 6
If this example is not sufficient to you, you can read the full article from where the example has been taken: How to convert ArrayList to HashMap in Java. Also, as you can see, the order HashMap does not maintain the order of ArrayList. In the above-mentioned link, you can find how to preserve the order of ArrayList while converting into the HashMap.

How to sort ArrayList in Java?

Java ArrayList Example 5: Create a list of strings and sort in ascending order

import java.util.Collections;
import java.util.Iterator;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> books = new ArrayList<>();
                books.add("Programming in Java");
                books.add("Let's Start JavaScript");
                books.add("Data Structures");
                books.add("Introduction to Algorithms");
                books.add("Concept of Databases");

                Collections.sort(books);

                books.forEach(bookName -> System.out.println(bookName));
        }
}
Output
Concept of Databases
Data Structures
Introduction to Algorithms
Let's Start JavaScript
Programming in Java

It is a very simple example to sort an ArrayList. If you want to learn how to sort an ArrayList in details, read this article: How to sort ArrayList in Java?.

How to remove duplicates from ArrayList in Java?

We can use LinkedHashSet to remove duplicates from ArrayList in Java as LinkedHashSet cannot store duplicate elements and also maintain the same insertion order as of the ArrayList.

Java ArrayList Example 6: Remove duplicates from ArrayList in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;

public class ArrayListExample {
     public static void main(String[] args) {
          ArrayList<String> languages = new ArrayList<>(
               Arrays.asList("Java", "C++", "Java", "Python", "C++", "Python", ".net"));
          System.out.println("All Languages : " + languages);

          ArrayList<String> uniqueLanguages = removeDuplicatesFromArrayList(languages);
          System.out.println("Unique Languages : " + uniqueLanguages);
     }
     private static <T> ArrayList<T> removeDuplicatesFromArrayList(ArrayList<T> arrayList) {
          LinkedHashSet<T> linkedHashSet = new LinkedHashSet<>();
          linkedHashSet.addAll(arrayList);
          ArrayList<T> uniqueList = new ArrayList<>(linkedHashSet);
          return uniqueList;
     }
}
Output
All Languages : [Java, C++, Java, Python, C++, Python, .net]
Unique Languages : [Java, C++, Python, .net]


How to compare two ArrayList in Java?

With the help of equals() method, we can compare two ArrayList in java and check whether they are same or not. But, here is a condition, the order of the elements of both the ArrayList must be the same. Otherwise, it won't work. To be sure, we can sort the ArrayList (sorting can be in ascending or descending) and then apply the equals() method for comparison.
Note : To do sorting, the type of ArrayList must implements the Comparable interface.

Java ArrayList Example 7: Compare two ArrayList in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class ArrayListCompareExample {
        public static void main(String[] args) {
                ArrayList<String> languageList1 = new ArrayList<>(
                        Arrays.asList("Java", "C++", "Python", "PHP", "NodeJS"));
                System.out.println("ArrayList 1: " + languageList1);

                ArrayList<String> languageList2 = new ArrayList<>(
                        Arrays.asList("C++", "Python", "PHP", "NodeJS", "Java"));
                System.out.println("ArrayList 2: " + languageList2);

                if (compareTwoArrayList(languageList1, languageList2)) {
                        System.out.println("Yes! Both the ArrayLists are same");
                } else {
                        System.out.println("No! ArrayLists are different");
                }
        }

        private static boolean compareTwoArrayList(ArrayList<String> arrayList1,
             ArrayList<String> arrayList2) {
                // Sort ArrayList in ascending order
                Collections.sort(arrayList1);
                Collections.sort(arrayList2);

                // Compare two ArrayList in Java: equality check
                return arrayList1.equals(arrayList2);
        }
}
Output
ArrayList 1: [Java, C++, Python, PHP, NodeJS]
ArrayList 2: [C++, Python, PHP, NodeJS, Java]
Yes! Both the ArrayLists are same

Read more about related to comparison of two ArrayList in Java.

How to serialize ArrayList in Java?

Here is a very basic example to serialize ArrayList of string objects. We can use writeObject() method of ObjectOutputStream to serialize ArrayList in Java.

Java ArrayList Example 8: Serialize ArrayList of strings

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                        Arrays.asList("Java", "C++", "NodeJS", "JavaScript", "Python"));
                try {
                        FileOutputStream fileOutputStream = new FileOutputStream("data");
                        ObjectOutputStream objectOutputStream 
                                        = new ObjectOutputStream(fileOutputStream);

                        objectOutputStream.writeObject(languageList);

                        objectOutputStream.close();
                        fileOutputStream.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
}

Related Posts:

Conclusion

In this article, we have learned various example programs related to ArrayList in Java. We can make our java programming more effective by learning these types of programs.

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…