Understanding List collection in Java with real life example

In this List Collection tutorial, we are going to learn what List interface offers, basically understanding the List Collection in Java with a real-life example.

Let’s take an example of a company, where you have thousands of employee. Now you got a requirement to sort the employee based on their seniority and show the result.  If you store your data in array type in that we need to either rely on database query for sorting or on your Java algorithm. This type of design may impact your application’s performance since you need to call again for your back-end for sorting. Instead, if you keep your employee data in List then you can easily sort the employees on the basis of seniority using collection.sort(). In this case, you are avoiding making any DB calls, this will give you the faster result.

Another example, of cricket. Like a series a going on or have been finished. Now, everyone wants to check out who are the contenders of Man of the series. To do so, we need a list of TOP run scorer or top wicket takers and for this, we need to sort the list of players on the basis of run scored and wicket taken. Check the below graphical example:

The List interface extends Java Collections and declares the behavior of a collection. Basically, a java list stores elements by insertion order (either at the end or at a specific position in the list). A list maintains indexes of its elements so it allows adding, retrieving, modifying, removing elements by an integer index.

Some properties of lists:

  • Elements of the lists interface are ordered using the Zero-based index.
  • One can access the elements of lists using an integer index.
  • Elements can be inserted at a specific position using integer index.
  • Elements can be removed from a specific position.
  • A list can contain duplicate elements and multiple null elements.

The List is the base interface for all list types, and the ArrayList and LinkedList java classes are two common list’s implementations.

  • ArrayList: An implementation that stores elements in a backing array. The array’s size will be automatically expanded if there isn’t enough room when adding new elements to the list.Therefore, ArrayList methods can be considered if we want fast, random access to the elements.
  • LinkedList: An implementation that stores elements in a doubly-linked list data structure. We can consider using a Linked List if fast adding and removing elements at the end of the list is required.

Methods Of List Interface:

  • void add(int index, Object obj): It is used to insert an element into the invoking list at the index passed in the index.

Example:

List li = new ArrayList();
li.add("element 1");
li.add("element 2"); 
li.add("element 3");
li.add(0, "element 0");
  • boolean addAll(int index, Collection c): It is used to insert all elements of c into the invoking list at the index passed in the index.

Example:

List li = new ArrayList();

        li.add(1);

        li.add(2);

        li.add(3);

// will add list li from 1 index

        l1.addAll(1, li);

        System.out.println(l1);
  • Object get(int index): It is used to return the object stored at the specified index within the invoking collection.

Example:

List li = new ArrayList();
li.add("element 0");
li.add("element 1");
li.add("element 2");

//access via index
String element0 = li.get(0);
String element1 = li.get(1);
String element2 = li.get(2);
  • int indexOf(Object obj): Returns the index of the first instance of obj in the invoking list.

Example:

public int indexOf(E e) {
    for (ListIterator<E> it = listIterator(); it.hasNext(); )
        if (e == null ? it.next() == null : e.equals(it.next()))
            return it.previousIndex();
    // Element not found
    return -1;
}
  • int lastIndexOf(Object obj): Returns the index of the last instance of obj in the invoking list.

Example:

List<String> li = new ArrayList<String>(5);

l.add("hello");

l.add("world");

l.add("how are you");

System.out.println("last index of world:" +li.lastIndexOf("world"));
  • ListIterator listIterator( ): It is used to return an iterator to the start of the invoking list.

Example:

List li = new ArrayList();
//add elements to list
Iterator iterator = li.iterator();
while(iterator.hasNext()) {
Object next = iterator.next();
}
  • ListIterator listIterator(int index): It is used to return an iterator to the start of the invoking list.

Example:

LinkedList <String> cities = new LinkedList <String> ();

cities.add(“Mumbai”);

cities.add(“Delhi”);

cities.add(“Noida”);

cities.add(“Pune”);

cities.add(“Indore”);

ListIterator <String> itr = cities.listIterator(2);

while(itr.hasNext()) {
System.out.println(“City:”+itr.next());
}
  • Object remove(int index): It is used to remove the element at position index from the invoking list and return the deleted element.

Example:

   List li = new ArrayList();

   li.add(1);

   li.add(2);

   li.add(3);

   l1.addAll(1, li);

   System.out.println(l1);
        
      l1.remove(1);                                   // remove element from index 1

      System.out.println(l1);
  • Object set(int index, Object obj): It is used to assign an element to the location specified by index within the invoking list.

Example:

public static <E> void swap(List<E> a, int i, int j) {
    E tmp = a.get(i);
   a.set(i, a.get(j));
    a.set(j, tmp);
}
  • List subList(int start, int end): Returns a list that includes elements from start to end in the invoking list.

Example:

ArrayList<String> li = new ArrayList<String>();

li.add(“white”);

li.add(“red”);

li.add(“blue”);

li.add(“yellow”);

System.out.println(“List of colors”+li);

ArrayList<String> l2 = new ArrayList<String>(li.subList(1,3));

System.out.println(“Portion of list”+l2);

Interface and class Description:

  • List Interface:
    • It is used to store the sequence of elements.
    • List Interface is implemented by ArrayList, Vector, LinkedList.
  • ArrayList Class:
    • This class extends AbstractList class and implements List Interface.
    • Provides functionality for dynamic array (shrink and grow).
    • Java 1.4 introduced the RandomAccess Interface, which the ArrayList implements.
  • Vector Class:
    • Vector class is similar to an ArrayList class, the vector methods are synchronized for thread – safety.
    • Apart from ArrayList class, only the Vector class implements the RandomAccess Interface.
  • LinkedList Class:
    • The LinkedList class extends the AbstractSequentialList class and implements the List Interface.
    • Similar to an ArrayList, a LinkedList is an ordered list based on the index position of elements. Elements here are doubly linked to one another.
    • Provides methods like addFirst(Object o), addLast(Object o).
    • LinkedList iterates slowly as compared to ArrayList, however, it facilitates fast insertion and deletion of elements.
    • With the release of Java 5, the LinkedList class has been enhanced to implement the Queue interface and supports methods.

Find the working example of List Collection from codedbug  Git Repo.

Most Frequently Asked Questions On List Interface

We require N+1 pointers, Where N is the size of your linked list. N pointers in each of the nodes and one head pointer that will allow you to perform any operation.
The only difference between them is that slow pointer travels the linked list one node at a time whereas a fast pointer travels the linked list two nodes at a time.
A doubly linked list would be a better choice because they allow fast and easy sequential access to the list in both directions.