Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on data, such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java?
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
Interfaces and its implementations, i.e., classes
Algorithm
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
No. | Method | Description |
1 | public boolean add(E e) | It is used to insert an element in this collection. |
2 | public boolean addAll(Collection<? extends E> c) | It is used to insert the specified collection elements in the invoking collection. |
3 | public boolean remove(Object element) | It is used to delete an element from the collection. |
4 | public boolean removeAll(Collection<?> c) | It is used to delete all the elements of the specified collection from the invoking collection. |
5 | default boolean removeIf(Predicate<? super E> filter) | It is used to delete all the elements of the collection that satisfy the specified predicate. |
6 | public boolean retainAll(Collection<?> c) | It is used to delete all the elements of invoking collection except the specified collection. |
7 | public int size() | It returns the total number of elements in the collection. |
8 | public void clear() | It removes the total number of elements from the collection. |
9 | public boolean contains(Object element) | It is used to search an element. |
10 | public boolean containsAll(Collection<?> c) | It is used to search the specified collection in the collection. |
11 | public Iterator iterator() | It returns an iterator. |
12 | public Object[] toArray() | It converts collection into array. |
13 | public <T> T[] toArray(T[] a) | It converts collection into array. Here, the runtime type of the returned array is that of the specified array. |
14 | public boolean isEmpty() | It checks if collection is empty. |
15 | default Stream<E> parallelStream() | It returns a possibly parallel Stream with the collection as its source. |
16 | default Stream<E> stream() | It returns a sequential Stream with the collection as its source. |
17 | default Spliterator<E> spliterator() | It generates a Spliterator over the specified elements in the collection. |
18 | public boolean equals(Object element) | It matches two collections. |
19 | public int hashCode() | It returns the hash code number of the collection. |
Iterator interface:-
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. | Method | Description |
1 | public boolean hasNext() | It returns true if the iterator has more elements otherwise it returns false. |
2 | public Object next() | It returns the element and moves the cursor pointer to the next element. |
3 | public void remove() | It removes the last elements returned by the iterator. It is less used. |
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
- Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the following example.
(Non-Synchronized means that two or more threads can access the methods of that particular class at any given time)
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi Vijay Ravi Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi Vijay Ravi Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
[Synchronization in java is the capability to control the access of multiple threads to any shared resource]
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.
Consider the following example.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.
Deque can be instantiated as:
Deque d = new ArrayDeque();
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:---
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.
Consider the following example.
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements.
The SortedSet can be instantiated as:
- SortedSet<data-type> set = new TreeSet();
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Consider the following example:
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
\==========================================================
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit.We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about the Java ArrayList class are:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because the array works on an index basis.
In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example:
ArrayList<int> al = ArrayList<int>(); // does not work
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies according to the elements getting added or removed from the list.
Hierarchy of ArrayList class
As shown in the above diagram, the Java ArrayList class extends AbstractList class which implements the List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
- public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Constructors of ArrayList
Constructor | Description |
ArrayList() | It is used to build an empty array list. |
ArrayList(Collection<? extends E> c) | It is used to build an array list that is initialized with the elements of the collection c. |
ArrayList(int capacity) | It is used to build an array list that has the specified initial capacity. |
Methods of ArrayList
Method | Description |
void add(int index, E element) | It is used to insert the specified element at the specified position in a list. |
boolean add(E e) | It is used to append the specified element at the end of a list. |
boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. |
boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. |
void clear() | It is used to remove all of the elements from this list. |
void ensureCapacity(int requiredCapacity) | It is used to enhance the capacity of an ArrayList instance. |
E get(int index) | It is used to fetch the element from the particular position of the list. |
boolean isEmpty() | It returns true if the list is empty, otherwise false. |
Iterator() | |
listIterator() | |
int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. |
Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order. |
<T> T[] toArray(T[] a) | It is used to return an array containing all of the elements in this list in the correct order. |
Object clone() | It is used to return a shallow copy of an ArrayList. |
boolean contains(Object o) | It returns true if the list contains the specified element. |
int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. |
E remove(int index) | It is used to remove the element present at the specified position in the list. |
boolean remove(Object o) | It is used to remove the first occurrence of the specified element. |
boolean removeAll(Collection<?> c) | It is used to remove all the elements from the list. |
boolean removeIf(Predicate<? super E> filter) | It is used to remove all the elements from the list that satisfies the given predicate. |
protected void removeRange(int fromIndex, int toIndex) | It is used to remove all the elements lies within the given range. |
void replaceAll(UnaryOperator<E> operator) | It is used to replace all the elements from the list with the specified element. |
void retainAll(Collection<?> c) | It is used to retain all the elements in the list that are present in the specified collection. |
E set(int index, E element) | It is used to replace the specified element in the list, present at the specified position. |
void sort(Comparator<? super E> c) | It is used to sort the elements of the list on the basis of the specified comparator. |
Spliterator<E> spliterator() | It is used to create a spliterator over the elements in a list. |
List<E> subList(int fromIndex, int toIndex) | It is used to fetch all the elements that lies within the given range. |
int size() | It is used to return the number of elements present in the list. |
void trimToSize() | It is used to trim the capacity of this ArrayList instance to be the list's current size. |
Java Non-generic Vs. Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it is type-safe, so typecasting is not required at runtime.
Let's see the old non-generic example of creating a Java collection.
- ArrayList list=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
- ArrayList<String> list=new ArrayList<String();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of object in it. If you try to add another type of object, it gives a compile-time error.
Java ArrayList Example
FileName: ArrayListExample1.java
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
[Mango, Apple, Banana, Grapes]
Iterating ArrayList using Iterator
Let's see an example to traverse ArrayList elements using the Iterator interface.
FileName: ArrayListExample2.java
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Output:
Mango
Apple
Banana
Grapes
Iterating ArrayList using For-each loop
Let's see an example to traverse the ArrayList elements using the for-each loop
FileName: ArrayListExample3.java
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Mango
Apple
Banana
Grapes
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set() method changes the element.
FileName: ArrayListExample4.java
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because index starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
How to Sort ArrayList
The java.util package provides a utility class Collections, which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
FileName: SortArrayList.java
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Ways to iterate the elements of the collection in Java
There are various ways to traverse the collection elements:
By Iterator interface.
By for-each loop.
By ListIterator interface.
By for loop.
By forEach() method.
By forEachRemaining() method.
Iterating Collection through remaining ways
Let's see an example to traverse the ArrayList elements through other ways
FileName: ArrayList4.java
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
System.out.println("Traversing list through List Iterator:");
//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
System.out.println("Traversing list through forEach() method:");
//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() method:");
Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}
Output:
Traversing list through List Iterator:
Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay
User-defined class objects in Java ArrayList
Let's see an example where we are storing Student class object in an array list.
FileName: ArrayList5.java
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name\=name;
this.age=age;
}
}
import java.util.*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s3=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Java ArrayList Serialization and Deserialization Example
Let's see an example to serialize an ArrayList object and then deserialize it.
FileName: ArrayList6.java
import java.io.*;
import java.util.*;
class ArrayList6 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
try
{
//Serialization
FileOutputStream fos=new FileOutputStream("file");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(al);
fos.close();
oos.close();
//Deserialization
FileInputStream fis=new FileInputStream("file");
ObjectInputStream ois=new ObjectInputStream(fis);
ArrayList list=(ArrayList)ois.readObject();
System.out.println(list);
}catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
[Ravi, Vijay, Ajay]
Java ArrayList example to add elements
Here, we see different ways to add an element.
FileName: ArrayList7.java
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
System.out.println("Initial list of elements: "+al);
//Adding elements to the end of the list
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After invoking add(E e) method: "+al);
//Adding an element at the specific position
al.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+al);
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al);
ArrayList<String> al3=new ArrayList<String>();
al3.add("John");
al3.add("Rahul");
//Adding second list elements to the first list at specific position
al.addAll(1, al3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+al);
}
}
Output:
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
Java ArrayList example to remove elements
Here, we see different ways to remove an element.
FileName: ArrayList8.java
import java.util.*;
class ArrayList8 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
//Creating another arraylist
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
al.addAll(al2);
System.out.println("Updated list : "+al);
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay"));//Here,we are using Lambdaexpression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
}
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []
Java ArrayList example of retainAll() method
FileName: ArrayList9.java
import java.util.*;
class ArrayList9{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
iterating the elements after retaining the elements of al2
Ravi
Java ArrayList example of isEmpty() method
FileName: ArrayList4.java
import java.util.*;
class ArrayList10{
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
System.out.println("Is ArrayList Empty: "+al.isEmpty());
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After Insertion");
System.out.println("Is ArrayList Empty: "+al.isEmpty());
}
}
Output:
Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false
Java ArrayList Example: Book
Let's see an ArrayList example where we are adding books to the list and printing all the books.
FileName: ArrayListExample20.java
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayListExample20 {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Size and Capacity of an ArrayList
Size and capacity of an array list are the two terms that beginners find confusing. Let's understand it in this section with the help of some examples. Consider the following code snippet.
FileName: SizeCapacity.java
import java.util.*;
public class SizeCapacity
{
public static void main(String[] args) throws Exception
{
ArrayList<Integer> al = new ArrayList<Integer>();
System.out.println("The size of the array is: " + al.size());
}
}
Output:
The size of the array is: 0
Explanation: The output makes sense as we have not done anything with the array list. Now observe the following program.
FileName: SizeCapacity1.java
import java.util.*;
public class SizeCapacity1
{
public static void main(String[] args) throws Exception
{
ArrayList<Integer> al = new ArrayList<Integer>(10);
System.out.println("The size of the array is: " + al.size());
}
}
Output:
The size of the array is: 0
Explanation: We see that the size is still 0, and the reason behind this is the number 10 represents the capacity not the size. In fact, the size represents the total number of elements present in the array. As we have not added any element, therefore, the size of the array list is zero in both programs.
Capacity represents the total number of elements the array list can contain. Therefore, the capacity of an array list is always greater than or equal to the size of the array list. When we add an element to the array list, it checks whether the size of the array list has become equal to the capacity or not. If yes, then the capacity of the array list increases. So, in the above example, the capacity will be 10 till 10 elements are added to the list. When we add the 11th element, the capacity increases. Note that in both examples, the capacity of the array list is 10. In the first case, the capacity is 10 because the default capacity of the array list is 10. In the second case, we have explicitly mentioned that the capacity of the array list is 10.
Note: There is no any standard method to tell how the capacity increases in the array list. In fact, the way the capacity increases vary from one GDK version to the other version. Therefore, it is required to check the way capacity increases code is implemented in the GDK. There is no any pre-defined method in the ArrayList class that returns the capacity of the array list. Therefore, for better understanding, use the capacity() method of the Vector class. The logic of the size and the capacity is the same in the ArrayList class and the Vector class.
\==========================================================
Java LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
Java LinkedList class can contain duplicate elements.
Java LinkedList class maintains insertion order.
Java LinkedList class is non synchronized.
In Java LinkedList class, manipulation is fast because no shifting needs to occur.
Java LinkedList class can be used as a list, stack or queue.
Hierarchy of LinkedList class
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and implements List and Deque interfaces.
Doubly Linked List
In the case of a doubly linked list, we can add or remove elements from both sides.
LinkedList class declaration
Let's see the declaration for java.util.LinkedList class.
- public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
Constructors of Java LinkedList
Constructor | Description |
LinkedList() | It is used to construct an empty list. |
LinkedList(Collection<? extends E> c) | It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection's iterator. |
Methods of Java LinkedList
Method | Description |
boolean add(E e) | It is used to append the specified element to the end of a list. |
void add(int index, E element) | It is used to insert the specified element at the specified position index in a list. |
boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. |
boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. |
boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. |
void addFirst(E e) | It is used to insert the given element at the beginning of a list. |
void addLast(E e) | It is used to append the given element to the end of a list. |
void clear() | It is used to remove all the elements from a list. |
Object clone() | It is used to return a shallow copy of an ArrayList. |
boolean contains(Object o) | It is used to return true if a list contains a specified element. |
Iterator<E> descendingIterator() | It is used to return an iterator over the elements in a deque in reverse sequential order. |
E element() | It is used to retrieve the first element of a list. |
E get(int index) | It is used to return the element at the specified position in a list. |
E getFirst() | It is used to return the first element in a list. |
E getLast() | It is used to return the last element in a list. |
int indexOf(Object o) | It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element. |
int lastIndexOf(Object o) | It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element. |
ListIterator<E> listIterator(int index) | It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list. |
boolean offer(E e) | It adds the specified element as the last element of a list. |
boolean offerFirst(E e) | It inserts the specified element at the front of a list. |
boolean offerLast(E e) | It inserts the specified element at the end of a list. |
E peek() | It retrieves the first element of a list |
E peekFirst() | It retrieves the first element of a list or returns null if a list is empty. |
E peekLast() | It retrieves the last element of a list or returns null if a list is empty. |
E poll() | It retrieves and removes the first element of a list. |
E pollFirst() | It retrieves and removes the first element of a list, or returns null if a list is empty. |
E pollLast() | It retrieves and removes the last element of a list, or returns null if a list is empty. |
E pop() | It pops an element from the stack represented by a list. |
void push(E e) | It pushes an element onto the stack represented by a list. |
E remove() | It is used to retrieve and removes the first element of a list. |
E remove(int index) | It is used to remove the element at the specified position in a list. |
boolean remove(Object o) | It is used to remove the first occurrence of the specified element in a list. |
E removeFirst() | It removes and returns the first element from a list. |
boolean removeFirstOccurrence(Object o) | It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail). |
E removeLast() | It removes and returns the last element from a list. |
boolean removeLastOccurrence(Object o) | It removes the last occurrence of the specified element in a list (when traversing the list from head to tail). |
E set(int index, E element) | It replaces the element at the specified position in a list with the specified element. |
Object[] toArray() | It is used to return an array containing all the elements in a list in proper sequence (from first to the last element). |
<T> T[] toArray(T[] a) | It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array. |
int size() | It is used to return the number of elements in a list. |
Java LinkedList Example
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay
Java LinkedList example to add elements
Here, we see different ways to add elements.
import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);
}
}
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
Java LinkedList example to remove elements
Here, we see different ways to remove an element.
import java.util.*;
public class LinkedList3 {
public static void main(String [] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add("Anuj");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Virat");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);
//Removing all the elements available in the list
ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []
Java LinkedList Example to reverse a list of elements
import java.util.*;
public class LinkedList4{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
//Traversing the list of elements in reverse order
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output: Ajay
Vijay
Ravi
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedListExample {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new LinkedList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Difference Between ArrayList and LinkedList
ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-synchronized classes.
However, there are many differences between the ArrayList and LinkedList classes that are given below.
ArrayList | LinkedList |
1) ArrayList internally uses a dynamic array to store the elements. | LinkedList internally uses a doubly linked list to store the elements. |
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the other elements are shifted in memory. | Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. |
3) An ArrayList class can act as a list only because it implements List only. | LinkedList class can act as a list and queue both because it implements List and Deque interfaces. |
4) ArrayList is better for storing and accessing data. | LinkedList is better for manipulating data. |
5) The memory location for the elements of an ArrayList is contiguous. | The location for the elements of a linked list is not contagious. |
6) Generally, when an ArrayList is initialized, a default capacity of 10 is assigned to the ArrayList. | There is no case of default capacity in a LinkedList. In LinkedList, an empty list is created when a LinkedList is initialized. |
7) To be precise, an ArrayList is a resizable array. | LinkedList implements the doubly linked list of the list interface. |
Example of ArrayList and LinkedList in Java
Let's see a simple example where we are using ArrayList and LinkedList both.
FileName: TestArrayLinked.java
import java.util.*;
class TestArrayLinked{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
List<String> al2=new LinkedList<String>();//creating linkedlist
al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay] linkedlist: [James,Serena,Swati,Junaid]
Points to Remember
The following are some important points to remember regarding an ArrayList and LinkedList.
When the rate of addition or removal rate is more than the read scenarios, then go for the LinkedList. On the other hand, when the frequency of the read scenarios is more than the addition or removal rate, then ArrayList takes precedence over LinkedList.
Since the elements of an ArrayList are stored more compact as compared to a LinkedList; therefore, the ArrayList is more cache-friendly as compared to the LinkedList. Thus, chances for the cache miss are less in an ArrayList as compared to a LinkedList. Generally, it is considered that a LinkedList is poor in cache-locality.
Memory overhead in the LinkedList is more as compared to the ArrayList. It is because, in a LinkedList, we have two extra links (next and previous) as it is required to store the address of the previous and the next nodes, and these links consume extra space. Such links are not present in an ArrayList.
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.
List Interface declaration
public interface List<E> extends Collection<E>
Java List Methods
Method | Description | |
void add(int index, E element) | It is used to insert the specified element at the specified position in a list. | |
boolean add(E e) | It is used to append the specified element at the end of a list. | |
boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of a list. | |
boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. | |
void clear() | It is used to remove all of the elements from this list. | |
boolean equals(Object o) | It is used to compare the specified object with the elements of a list. | |
int hashcode() | It is used to return the hash code value for a list. | |
E get(int index) | It is used to fetch the element from the particular position of the list. | |
boolean isEmpty() | It returns true if the list is empty, otherwise false. | |
int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. | |
Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order. | |
<T> T[] toArray(T[] a) | It is used to return an array containing all of the elements in this list in the correct order. | |
boolean contains(Object o) | It returns true if the list contains the specified element | |
boolean containsAll(Collection<?> c) | It returns true if the list contains all the specified element | |
int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. | |
E remove(int index) | It is used to remove the element present at the specified position in the list. | |
boolean remove(Object o) | It is used to remove the first occurrence of the specified element. | |
boolean removeAll(Collection<?> c) | It is used to remove all the elements from the list. | |
void replaceAll(UnaryOperator<E> operator) | It is used to replace all the elements from the list with the specified element. | |
void retainAll(Collection<?> c) | It is used to retain all the elements in the list that are present in the specified collection. | |
E set(int index, E element) | It is used to replace the specified element in the list, present at the specified position. | |
void sort(Comparator<? super E> c) | It is used to sort the elements of the list on the basis of specified comparator. | |
Spliterator<E> spliterator() | It is used to create spliterator over the elements in a list. | |
List<E> subList(int fromIndex, int toIndex) | It is used to fetch all the elements lies within the given range. | |
int size() | It is used to return the number of elements present in the list. |
Java List vs ArrayList
List is an interface whereas ArrayList is the implementation class of List.
How to create List
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List:
//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();
//Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();
//Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book>();
//Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();
In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to specify the type. Here, T denotes the type.
Java List Example
Let's see a simple example of List where we are using the ArrayList class as the implementation.
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Mango
Apple
Banana
Grapes
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String lang:array){
list.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Output:
Printing Array: [Java, Python, PHP, C++] Printing List: [Java, Python, PHP, C++]
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
fruitList.add("Mango");
fruitList.add("Banana");
fruitList.add("Apple");
fruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
}
Output:
Printing Array: [Mango, Banana, Apple, Strawberry] Printing List: [Mango, Banana, Apple, Strawberry]
Get and Set Element in List
The get() method returns the element at the given index, whereas the set() method changes or replaces the element.
import java.util.*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0
//changing the element
list.set(1,"Dates");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
How to Sort List
There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element. The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort any List.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Java ListIterator Interface
ListIterator Interface is used to traverse the element in a backward and forward direction.
ListIterator Interface declaration
- public interface ListIterator<E> extends Iterator<E>
Methods of Java ListIterator Interface:
Method | Description |
void add(E e) | This method inserts the specified element into the list. |
boolean hasNext() | This method returns true if the list iterator has more elements while traversing the list in the forward direction. |
E next() | This method returns the next element in the list and advances the cursor position. |
int nextIndex() | This method returns the index of the element that would be returned by a subsequent call to next() |
boolean hasPrevious() | This method returns true if this list iterator has more elements while traversing the list in the reverse direction. |
E previous() | This method returns the previous element in the list and moves the cursor position backward. |
E previousIndex() | This method returns the index of the element that would be returned by a subsequent call to previous(). |
void remove() | This method removes the last element from the list that was returned by next() or previous() methods |
void set(E e) | This method replaces the last element returned by next() or previous() methods with the specified element. |
Example of ListIterator Interface
import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
}
}
Output:
Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit
Example of List: Book
Let's see an example of List where we are adding the Books.
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ListExample5 {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); }
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications and Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6
Subscribe to my newsletter
Read articles from Divya Bhushan Dewangan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Divya Bhushan Dewangan
Divya Bhushan Dewangan
I am full stack developer having keen interest in MERN stack and core Java with RDBMS.