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