How to use ArrayList in Java with Example Programs

How to use ArrayList in Java with Example Programs

Java ArrayList is a dynamic array with resizable-array implementation of Java List interface. In the tutorial, we will learn how to use Java ArrayList by examples:

  • What is Java ArrayList?
  • How to construct a Java ArrayList?
  • Do a Set Operations with Java ArrayList
  • How to Sort Java ArrayList?
  • Use Java ArrayList with Multi-Thread Environment

Related posts:
How to use Java Stack with Examples
How to use Java PriorityQueue with Examples

Java ArrayList

– Java ArrayList is resizable-array implementation of Java List interface.
+ When adding new elements, Java ArrayList grows its size automatically.
+ When the elements are removed, Java ArrayList shrinks the size.

– Java ArrayList permits all elements, including null. But Java ArrayList can NOT contain primative elements such int, boolean, char… Java ArrayList can contains object elements like: Integer, String, Boolean…, or User Defined Objects.
– Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. For reducing the amount of incremental reallocation, we can increase the capacity of an ArrayList instance before adding a large number of elements.
– The ArrayList implementation is not synchronized. To prevent accidental unsynchronized access to the list, we use the solution:

List list = Collections.synchronizedList(new ArrayList(...));

Here is the hierarchy of Java ArrayList:

How to use ArrayList in Java with Example Programs - hierarchy

How to Initialize ArrayList in Java with Examples

– To construct an empty Java Arraylist, we can use the below constructor:

public ArrayList()

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		System.out.println(arrayList);
		// []
		
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		
		System.out.println(arrayList);
		
		// [1, 10, 7, 4, 11]
	}
}

– We can construct a Java ArrayList that contains the elements of the specified collection with following constructor:

public ArrayList(Collection c)

-> It throws NullPointerException if the specified collection is null.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		
		List newArrayList = new ArrayList(arrayList);
		System.out.println(newArrayList);
		// [1, 10, 7, 4, 11]
	}
}

How to Add an Element to Java ArrayList with Examples

– To add an element to an Java ArrayList, we can use the add method:

public boolean add(E e)

-> It appends a specified element to the end of the Java ArrayList.

Examples:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		System.out.println(arrayList);
		// Output -> Empty List
		// []
		
		// -> add elements to arrayList
		arrayList.add(1);
		System.out.println(arrayList);
		// -> [1]
		
		arrayList.add(10);
		System.out.println(arrayList);
		// -> [1, 10]
		
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11]
	}
}

– We can insert the specified element at the specified position in an Java ArrayList with following add signature method:

public void add(int index, E element)

It shifts the element currently at that position (if any) and any subsequent elements to the right.

There are 2 parameters in above signature:

  • index: is the position which the specified element is to be inserted
  • element: the item to be inserted

If the index is out of the range, the above add method will throw IndexOutOfBoundsException.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11]
		
		
		// -> add an element at a specific position
		arrayList.add(3, 99);
		
		System.out.println(arrayList);
		// [1, 10, 7, 99, 4, 11]
	}
}

How to Add a Collection to Java ArrayList with Examples

We can add a Collection to a Java ArrayList with addAll method:

addAll(int index, Collection c)

-> It helps to append all of the elements in the specified collection to the end of Java ArrayList.
If the specified collection is null, a NullPointerException will be throwed.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		// Create a new array list
		List newArrayList = new ArrayList();
		
		// Add a collection to new array list
		newArrayList.addAll(arrayList);
		
		System.out.println(newArrayList);
		// [1, 10, 7, 4, 11]
		
		newArrayList.addAll(arrayList);
		System.out.println(newArrayList);
		// [1, 10, 7, 4, 11, 1, 10, 7, 4, 11]
	}
}

We also can insert all of the elements in the specified collection into the Java ArrayList, and starting at the specified position by using following addAll signature method:

public boolean addAll(int index, Collection c)

It throws exceptions when:

  • if the index is out of range (index < 0 || index > size()), throws IndexOutOfBoundsException
  • if the specified collection is null, throws NullPointerException

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		// Create a new Array List
		List newArrayList = new ArrayList();
		// Add a collection to new array list
		newArrayList.addAll(arrayList);
		
		System.out.println(newArrayList);
		// [1, 10, 7, 4, 11]
		
		// Insert the collection at a specific index
		newArrayList.addAll(2, arrayList);
		System.out.println(newArrayList);
		// [1, 10, 1, 10, 7, 4, 11, 7, 4, 11]
	}
}

How to Iterate Through ArrayList in Java with Examples

To iterate through a Java ArrayList, we can use one of the following solution:

  • Use an normal Loop statement to travel through Java ArrayList
  • Use the Loop statement with index to iterate through Java ArrayList
  • Use forEch method
  • Use iterator() method
  • Combine iterator() method and forEachRemaining() method
  • Use the listIterator() to traverse backwards Java ArrayList
  • Use Java Stream to iterate through a Java ArrayList

– We just use an normal loop solution to travel through Java ArrayList as following example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		for(Integer value: arrayList) {
			System.out.println(value);
		}
		/*
			1
			10
			7
			4
			11
		 */
	}
}

– We use the loop statement with index to iterate through Java ArrayList:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		for(int i=0; i

- We can use forEch method:

public void forEach(Consumer action)

-> It performs the given action for each element of the Iterable.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		arrayList.forEach(System.out::println);
		/*
			1
			10
			7
			4
			11
		 */
	}
}

- We can use iterator() method:

public Iterator iterator()

-> The method returns an iterator over the elements in the Arraylist in proper sequence.

Example:

package com.grokonez.arraylist;

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

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		
		Iterator iterator = arrayList.iterator();
		while(iterator.hasNext()) {
			Integer e = iterator.next();
			System.out.println(e);
		}
		/*
			1
			10
			7
			4
			11
		 */
	}
}

- We can combine iterator() method and forEachRemaining() method to travel through Java ArrayList:

package com.grokonez.arraylist;

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

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		Iterator iterator = arrayList.iterator();
		iterator.forEachRemaining(System.out::println);
		/*
			1
			10
			7
			4
			11
		 */
	}
}

- We also can use the listIterator() to to traverse backwards Java ArrayList:

ListIterator listIterator();

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		
		ListIterator lstIterator = arrayList.listIterator(arrayList.size());
		while(lstIterator.hasPrevious()) {
			System.out.println(lstIterator.previous());
		}
		/*
			11
			4
			7
			10
			1
		 */
	}
}

- We can use Java Stream to iterate through a Java ArrayList:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		arrayList.stream().forEach(System.out::println);
		/*
			1
			10
			7
			4
			11
		 */
	}
}

How to Get/Set Elements in Java ArrayList with Examples

We can get/set Java ArrayList elements by get() and set() methods:

- Get method signature:

public E get(int index)
-> index: index of the element to return
-> if the index is out of range, IndexOutOfBoundsException will be throwed.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		System.out.println(arrayList);
		// [1, 10, 7, 4, 11]
		
		/*
		 * Get the element at the specified position in the Java ArrayList.
		 */
		Integer value = arrayList.get(2);
		System.out.println(value);
		// 7
		
		value = arrayList.get(4);
		System.out.println(value);
		// 11
	}
}

- Set method signature:

public E set(int index, E element)

-> if the index is out of range, IndexOutOfBoundsException will be throwed.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		System.out.println(arrayList);
		// [1, 10, 7, 4, 11]
	
		/*
		 *  Replaces the element at the specified position in this list
		 */
		arrayList.set(1, 21);
		arrayList.set(3, 35);
		
		System.out.println(arrayList);
		// [1, 21, 7, 35, 11]
	}
}

-> Output:

[1, 10, 7, 4, 11]
[1, 21, 7, 35, 11]

How to Remove Elements in Java ArrayList with Examples

We have a set of operations to remove element in Java ArrayList:

  • Removes the element at the specified position.
  • Removes the first occurrence of the specified element.
  • Removes all of its elements from the Java ArrayList that are contained in the specified collection.
  • Removes all of the elements of the Java ArrayList that pass the given predicate.
  • Removes all of the elements from the Java ArrayList.

How to Removes Element at the Specified Position Examples?

- We use the method: public E remove(int index)
-> It removes the element at the specified position and shifts any subsequent elements to the left.
-> if the index is out of the range, IndexOutOfBoundsException will be throwed.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);

		System.out.println(arrayList);
		// [1, 10, 7, 4, 11]
	
		/*
		 *  Removes the element at the specified position.
		 */
		arrayList.remove(2);
		
		System.out.println(arrayList);
		// [1, 10, 4, 11]
		
		arrayList.remove(1);
		System.out.println(arrayList);
		// [1, 4, 11]
	}
}

How to removes the first occurrence of the specified element?
- We use the method signature:

public boolean remove(Object o)

-> Removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i)))

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add("one");
		arrayList.add("ten");
		arrayList.add("seven");
		arrayList.add("four");
		arrayList.add("eleven");
		arrayList.add("seven");

		System.out.println(arrayList);
		// [one, ten, seven, four, eleven, seven]
	
		/*
		 *  Removes the first occurrence of the specified element
		 */
		arrayList.remove("ten");
		
		System.out.println(arrayList);
		// [one, seven, four, eleven, seven]
		
		arrayList.remove("seven");
		
		System.out.println(arrayList);
		// [one, four, eleven, seven]
	}
}

How to removes all elements from Java ArrayList that are contained in the specified collection?

-> We use the below method signature:
public boolean removeAll(Collection c)

The above will throw 2 exceptions:

  • ClassCastException: if the class of an element of the Java ArrayList is incompatible with the specified collection
  • NullPointerException: if this Java ArrayList contains a null element and the specified collection does not permit null elements, or if the specified collection is null

Example:

package com.grokonez.arraylist;

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

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add("one");
		arrayList.add("ten");
		arrayList.add("seven");
		arrayList.add("four");
		arrayList.add("eleven");
		arrayList.add("seven");

		System.out.println(arrayList);
		// [one, ten, seven, four, eleven, seven]
	
		/*
		 *  Removes all elements from Java ArrayList that are contained in the specified collection
		 */
		arrayList.removeAll(Arrays.asList("ten", "seven"));
		
		System.out.println(arrayList);
		// [one, four, eleven]
	}
}

How to removes all of the elements of the Java ArrayList that pass the given Predicate?
-> We can use the below method signature:

removeIf(Predicate filter)

- filter: a predicate which returns true for elements to be removed.

Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		/* 
		 * Remove all even numbers
		 */
		arrayList.removeIf(i -> i%2==0);
		
		System.out.println(arrayList);
		// [1, 7, 11, 7]
	}
}

How to removes all of the elements from the Java ArrayList?
-> We use clear() method:

public void clear()

- It removes all of the elements from the Java ArrayList.

Example:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		/* 
		 * Remove all even numbers
		 */
		arrayList.clear();
		
		System.out.println(arrayList);
		// []
	}
}

How to Search an Element in Java ArrayList with Examples

To find out an element in Java ArrayList, we can use two methods:

  • indexOf
  • lastIndexOf

- indexOf method:

public int indexOf(Object o)

-> Returns the index of the first occurrence of the specified element in this list.
-> Or -1 if this list does not contain the element.

Example:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		int index = arrayList.indexOf(7);
		System.out.println(index);
		// 2
		
		index = arrayList.indexOf(11);
		System.out.println(index);
		// 4 
	}
}

- lastIndexOf signature method:

public int lastIndexOf(Object o)

-> Returns the index of the last occurrence of the specified element in this list
-> or -1 if this list does not contain the element

Example:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println(arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		int index = arrayList.lastIndexOf(7);
		System.out.println(index);
		// 5
		
		index = arrayList.indexOf(11);
		System.out.println(index);
		// 4 
	}
}

How to Get a View from Java ArrayList with Examples

We use subList to get a view of the portion of the Java ArrayList between the specified fromIndex, inclusive, and toIndex, exclusive.

- Method Signature:

public List subList(int fromIndex, int toIndex)

It may be throw Exceptions:

  • IndexOutOfBoundsException will be throwed if fromIndex < 0 || toIndex > size
  • IllegalArgumentException will be throwed if fromIndex > toIndex

Example:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		/*
		 * Get a View from Java ArrayList
		 */
		List view = arrayList.subList(1, 4);
		System.out.println(view);
		// [10, 7, 4]
		
		view = arrayList.subList(2, 5);
		System.out.println(view);
		// [7, 4, 11]
	}
}

How to Create Java ArrayList of Custom Objects with Examples

Now We create a Java ArrayList with Custom User defined Object,

- Create Developer class:

class Developer{
	  Integer id;
	  String name;
	  Double salary;
	  
	  public Developer(Integer id, String name, Double salary){
	    this.id = id;
	    this.name = name;
	    this.salary = salary;
	  }
	  
	  public int getId() {
	    return this.id;
	  }
	  
	  public String getName() {
	    return this.name;
	  }
	  
	  public Double getSalary() {
	    return this.salary;
	  }
	  
	  public String toString() {
	    return String.format("[id = %d, name = %s, salary = %.2f]", id, name, salary);
	  }	
}

- Create Developer Java ArrayList:

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 List devs = new ArrayList();
		// -> add elements to arrayList
		 devs.add(new Developer(1, "Jack", 6000.0));
		 devs.add(new Developer(4, "Joe", 7000.0));
		 devs.add(new Developer(10, "Davis", 6500.0));
		 devs.add(new Developer(6, "Mary", 5700.0));
		
		 /*
		  * Iterate through Java ArrayList
		 */
		 devs.forEach(System.out::println);
		 /*
			[id = 1, name = Jack, salary = 6000,00]
			[id = 4, name = Joe, salary = 7000,00]
			[id = 10, name = Davis, salary = 6500,00]
			[id = 6, name = Mary, salary = 5700,00]
		  */
	}
}

- Implement equals method in Developer class for comparing objects:

@Override
public boolean equals(Object o) {
	if (this == o)
		return true;
	if (o == null || getClass() != o.getClass())
		return false;
	
	Developer developer = (Developer) o;
	
	return Integer.compare(developer.id, id) == 0
			&& Objects.equals(name, developer.name)
			&& Double.compare(developer.salary, salary) == 0;
}

- Now we can find a Developer as below code:

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 List devs = new ArrayList();
		// -> add elements to arrayList
		 devs.add(new Developer(1, "Jack", 6000.0));
		 devs.add(new Developer(4, "Joe", 7000.0));
		 devs.add(new Developer(10, "Davis", 6500.0));
		 devs.add(new Developer(6, "Mary", 5700.0));
		
		 /*
		  * Iterate through Java ArrayList
		 */
		 devs.forEach(System.out::println);
		 /*
			[id = 1, name = Jack, salary = 6000,00]
			[id = 4, name = Joe, salary = 7000,00]
			[id = 10, name = Davis, salary = 6500,00]
			[id = 6, name = Mary, salary = 5700,00]
		  */
		 
		 /*
		  * Find a Developer
		  */
		 int index = devs.indexOf(new Developer(10, "Davis", 6500.0) );
		 Developer davis = devs.get(index);
		 System.out.println("Davis is " + davis);
		 // [id = 10, name = Davis, salary = 6500,00]
	}
}

How to Sort ArrayList in Java with Examples

We have 2 solution for sorting Java ArrayList:

  • Using the method void sort(Comparator c) of a Java ArrayList instance
  • Using the method void sort(List list, Comparator c) of Collection interface

Let's do details!

- Using the sort() method of an ArrayList instance:

public void sort(Comparator c)

-> It sorts the ArrayList according to the order induced by the specified Comparator.

Example:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Comparator;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println("Orignal ArrayList: " + arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		/*
		 * Sorting
		 */
		arrayList.sort(Comparator.naturalOrder());
		System.out.println("Sorted ArrayList: " + arrayList);
		// [1, 4, 7, 7, 10, 11]
	}
}

- In the following example, we define a Comparator for sorting a String ArrayList by the length:

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Comparator;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add("Dorothy");
		arrayList.add("Bob");
		arrayList.add("Kimberly");
		arrayList.add("Lisa");
		arrayList.add("Andrew");
		arrayList.add("Paul");
		
		System.out.println(arrayList);
		// [Dorothy, Bob, Kimberly, Lisa, Andrew, Paul]
	
		/*
		 * Sorting
		 */
		arrayList.sort(new Comparator() {
			public int compare(String s1, String s2) {
				return s1.length() - s2.length();
			}
		});
		
		System.out.println(arrayList);
		// [Bob, Lisa, Paul, Andrew, Dorothy, Kimberly]
	}
}

- Now We use Collection.sort() method for sorting:

public static void sort(List list, Comparator c)

+ Example Sorting Integer Java ArrayList using Collections.sort():

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 List arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add(1);
		arrayList.add(10);
		arrayList.add(7);
		arrayList.add(4);
		arrayList.add(11);
		arrayList.add(7);
		
		System.out.println("Orignal ArrayList: " + arrayList);
		// [1, 10, 7, 4, 11, 7]
	
		/*
		 * Sorting
		 */
		Collections.sort(arrayList, Comparator.naturalOrder());
		
		System.out.println("Sorted ArrayList: " + arrayList);
		// [1, 4, 7, 7, 10, 11]
	}
}

+ Example Sorting String Java ArrayList using Collection.sort():

package com.grokonez.arraylist;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 AbstractList arrayList = new ArrayList();
		// -> add elements to arrayList
		arrayList.add("Dorothy");
		arrayList.add("Bob");
		arrayList.add("Kimberly");
		arrayList.add("Lisa");
		arrayList.add("Andrew");
		arrayList.add("Paul");
		
		System.out.println(arrayList);
		// [Dorothy, Bob, Kimberly, Lisa, Andrew, Paul]
	
		/*
		 * Sorting
		 */
		Collections.sort(arrayList, new Comparator() {
			public int compare(String s1, String s2) {
				return s1.length() - s2.length();
			}
		});
		
		System.out.println(arrayList);
		// [Bob, Lisa, Paul, Andrew, Dorothy, Kimberly]
	}
}

+ Example Sorting User Custom Defined Object by Salary property using Collection.sort():

public class JavaArrayListExamples {
	public static void main(String[] args) {
		 List devs = new ArrayList();
		// -> add elements to arrayList
		 devs.add(new Developer(1, "Jack", 6000.0));
		 devs.add(new Developer(4, "Joe", 7000.0));
		 devs.add(new Developer(10, "Davis", 6500.0));
		 devs.add(new Developer(6, "Mary", 5700.0));
		
		 /*
		  * Iterate through Java ArrayList
		 */
		 devs.forEach(System.out::println);
		 /*
			[id = 1, name = Jack, salary = 6000,00]
			[id = 4, name = Joe, salary = 7000,00]
			[id = 10, name = Davis, salary = 6500,00]
			[id = 6, name = Mary, salary = 5700,00]
		  */
		 
		 /*
		  * Sorting Developer ArrayList using Collections.sort()
		  */
		 Collections.sort(devs, new Comparator(){
			@Override
			public int compare(Developer o1, Developer o2) {
				return (int) (o1.getSalary() - o2.getSalary());
			}
		 });
		 
		 System.out.println("---Sorting Devs List---");
		 devs.forEach(System.out::println);
		 /*
			[id = 6, name = Mary, salary = 5700,00]
			[id = 1, name = Jack, salary = 6000,00]
			[id = 10, name = Davis, salary = 6500,00]
			[id = 4, name = Joe, salary = 7000,00]		  
		  */
	}
}

How to Synchronize ArrayList in Java with Examples

As we know, the Java ArrayList implementation is not synchronized. So we can try to simulate a multi-thread environment to prove it.

- Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JavaArrayListExamples {
	
    public static void main(String[] args) throws InterruptedException {
        List intList = new ArrayList<>();
        intList.add(0);
        intList.add(0);

        // Initialize a Thread Pool
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        // Create a Runnable task that increments each element of the ArrayList by one
        Runnable task = () -> {
        	adding(intList);
        };

        // Submit 200 tasks to the executorService.
        for(int i = 0; i < 200; i++) {
            executorService.submit(task);
        }

        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        
        System.out.println(intList);
        // [194, 200]
    }

    // Increments each element of the ArrayList by one
    private static void adding(List intList) {
        for(int i = 0; i < intList.size(); i++) {
            Integer value = intList.get(i);
            intList.set(i, value + 1);
        }
    }
}

-> Output:

// [194, 200]

In above example, we create a multi-thread environment with 20 threads and submit 200 tasks to process. Each task just does a simple work: incrementing each element of the ArrayList by one.
So the expected output should be [200, 200]. But NOT right, the real output is non-deterministic for each running time, such as [194, 200] or [198, 199]...

Why?
-> Beacause each Thread might overrides the changes of the others.

How to create a propery solution?
-> We need create a synchronized view of the ArrayList as below code:

List intList = Collections.synchronizedList(new ArrayList<>());

-> Then blocking the implementation of function void adding(List intList) by using synchronized keyword to make sure that no having more than 1 thread doing the modification on the ArrayList instance at a specified time.

- Example:

package com.grokonez.arraylist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JavaArrayListExamples {
	
    public static void main(String[] args) throws InterruptedException {
        List intList  = Collections.synchronizedList(new ArrayList<>());
        
        intList.add(0);
        intList.add(0);

        // Initialize a Thread Pool
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        // Create a Runnable task that increments each element of the ArrayList by one
        Runnable task = () -> {
        	adding(intList);
        };

        // Submit 200 tasks to the executorService.
        for(int i = 0; i < 200; i++) {
            executorService.submit(task);
        }

        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        
        System.out.println(intList);
        // [200, 200]
    }

    // Increments each element of the ArrayList by one
    private static void adding(List intList) {
    	synchronized (intList) {
            for(int i = 0; i < intList.size(); i++) {
                Integer value = intList.get(i);
                intList.set(i, value + 1);
            }			
		}
    }
}

-> Output:

[200, 200]

Conclusion

Thanks for reading, We had learned:
- What is Java ArrayList?
- And how to use Java ArrayList with examples?

  • How to Add an Element to Java ArrayList
  • How to Add a Collection to Java ArrayList
  • How to Iterate Through ArrayList in Java
  • How to Get/Set Elements in Java ArrayList
  • How to Remove Elements in Java ArrayList
  • How to Search an Element in Java ArrayList
  • How to Get a View from Java ArrayList
  • How to create Java ArrayList of Custom User Defined Objects
  • How to Sort ArrayList in Java with Integer, String and User Defined Objects types
  • How to Synchronize Java ArrayList

Happy Learning! See you later!



By grokonez | May 19, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*