Java Collections Generics List and ArrayList Methods Usage tutorial

Java Collections Generics List and ArrayList Method Usage tutorial:

The code below contains usage of various collection framework methods with overloaded mehtods such as add, addAll, set, get, contains, remove, sort, isEmpty. Also usage of iterator, list iterator, comparator, enhanced for loop, foeEach, lambda expression, list to array conversion, adding Integer list items to string list, custom data structure list of lists etc.

Get the Latest code from my Github repository here:

https://github.com/quickgrid/JavaProgramming/blob/master/src/javacode/collectionsexample/ListTest.java

If you have trouble reading the code head over to the github link. Github source is a lot easier on the eyes than reading here.

Please delete or modify the package statement if your folder structure is different.

list tutorial output 1
list tutorial output 1
list tutorial output 2
list tutorial output 2
list tutorial output 3
list tutorial output 3

 

Code:

package javacode.collectionsexample;

import java.util.*;

/**
 * Created by asif on 9/2/2015.
 */
public class ListTest {
    public static void main(String [] args){


        /*******************************************************************************************/
        // Creating a generic String list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 1:");
        System.out.println("===========");


        // It is optional to write string inside angle brackets " new ArrayList<String>() "
        List<String> list1 = new ArrayList<>();

        // Add items to the list
        // since the list was string type trying to put other variables types will result in error
        for(int i = 0; i < 5; ++i)
            list1.add(i + "");

        // See how many elements are in the list
        System.out.println("Items in the list 1: " + list1.size());


        System.out.println();
        /*******************************************************************************************/
        // Adding items in for loop
        /*******************************************************************************************/
        System.out.println("TUTORIAL 2:");
        System.out.println("===========");

        List<String> list2 = new ArrayList<>();

        for(int i = 4; i >= 0; --i)
            list2.add(i + "");

        System.out.println("Items in the list 2: " + list2.size());


        System.out.println();
        /*******************************************************************************************/
        // Checking if all items in a collection exist in another collection
        /*******************************************************************************************/
        System.out.println("TUTORIAL 3:");
        System.out.println("===========");


        int index = 0;

        // Both list contains same items but they are in different order
        // So here it checks if all items from one collection is available in another collection
        if(list1.containsAll(list2)){

            // just like array we can access or get elements by its index
            System.out.println("Elements in the given " + index + " index: (list1["+ index + "], list2[" + index + "]) = (" + list1.get(index) + ", " + list2.get(index) + ")");

        }


        System.out.println();
        /*******************************************************************************************/
        // Checking if a list contains a certain item
        /*******************************************************************************************/
        System.out.println("TUTORIAL 4:");
        System.out.println("===========");


        // Check if a certain element belongs to a collection
        String my_element = "3";

        if(list2.contains( my_element )){

            // Now that we know that the collections contains the given element lets get the index
            System.out.println("List contains given element at index: " + list2.indexOf(my_element));

        }


        System.out.println();
        /*******************************************************************************************/
        // Using iterator to traverse a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 5:");
        System.out.println("===========");


        // append all the items in list2 to list1
        list1.addAll(list2);

        // Create an iterator to iterate over all the items in list
        Iterator iterator = list1.iterator();

        // using hasNext to check if the next element exist
        while (iterator.hasNext()){
            System.out.print(iterator.next() + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Adding items to a generic Integer list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 6:");
        System.out.println("===========");


        // create a new list of integers
        List<Integer> list3 = new ArrayList<>();

        for (int i = 0; i < 5 ; ++i) {
            list3.add( i * 2 );
        }

        System.out.print("Current list 3 items: ");

        // Enhanced for loop to print current items in list2
        for(Integer i : list3){
            System.out.print(i + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Converting a list to an array
        /*******************************************************************************************/
        System.out.println("TUTORIAL 7:");
        System.out.println("===========");


        // Convert list of integer into an integer array
        Integer[] array = new Integer[list3.size()];
        list3.toArray(array);

        System.out.print("After conversion of list 3 to array: ");

        for (int i = 0; i < array.length; ++i) {
            System.out.print(array[i] + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Printing list items using forEach lambda expression
        /*******************************************************************************************/
        System.out.println("TUTORIAL 8:");
        System.out.println("===========");


        list3.forEach(
                // Lambda expression
                // In the loop add each elements in list3 to list2
                // since list3 is of Integer type and list2 is of String Type and i am adding to list2
                // So each item of list2 should be cast to String
                items -> list2.add(Integer.toString(items))
        );

        System.out.print("After adding list3 to list2: ");

        // Using Stream to print all items in the list
        list2.forEach(
                // java will try to determine the type
                i -> System.out.print(i + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Adding an item to the list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 9:");
        System.out.println("===========");


        // Add items in the list 2 adds to last position of the list
        list2.add("Asif");

        System.out.print("After calling add function: ");
        list2.forEach(i -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Add object at a specific index
        /*******************************************************************************************/
        System.out.println("TUTORIAL 10:");
        System.out.println("===========");


        // An overload add method takes an index to place in as first argument
        // The second argument is the element to add
        list2.add(1, "Quickgrid");

        System.out.print("After calling overloaded add function: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Remove object at a specific index
        /*******************************************************************************************/
        System.out.println("TUTORIAL 11:");
        System.out.println("===========");


        // It will remove the item on the 0th position of the list
        list2.remove(0);

        System.out.print("After calling remove with index: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Sort a list using default comparators
        /*******************************************************************************************/
        System.out.println("TUTORIAL 12:");
        System.out.println("===========");


        // It will Sort the list with default comparator
        list2.sort(Comparator.<String>naturalOrder());

        System.out.print("After Sorting list 2 with comparator : ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Replacing object at a given location
        /*******************************************************************************************/
        System.out.println("TUTORIAL 13:");
        System.out.println("===========");


        // It will replace an element in the given index
        list2.set(1, "Almost there");

        System.out.print("After replacing given index with an item: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Getting a specific sub list from a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 14:");
        System.out.println("===========");


        System.out.print("Print the sublist from a given index to another index: ");

        // Print the sublist from a given index to another index
        System.out.println(list2.subList(2, 8));


        System.out.println();
        /*******************************************************************************************/
        // Iterating list backwards using bidirectional ListIterator
        /*******************************************************************************************/
        System.out.println("TUTORIAL 15:");
        System.out.println("===========");


        // Print list 3 in reverse order using bidirectional ListIterator
        // Takes an optional parameter from which index to start from
        ListIterator<Integer> iit = list3.listIterator(list3.size());

        System.out.print("Traversing list 3 in reverse order using ListIterator: ");

        while (iit.hasPrevious()){
           System.out.print(iit.previous() + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Clearing or emptying a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 16:");
        System.out.println("===========");


        // Delete all items in the list
        list3.clear();

        // Check if the list is empty
        if(list3.isEmpty()){
            System.out.println("End of tutorial.....");
        }


        System.out.println();
        /*******************************************************************************************/
        // Creating a custom data structure using list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 17:");
        System.out.println("===========");


        // Creating custom data structure list of lists
        List< List<String> > listOfList = new ArrayList<>();
        listOfList.add(list1);
        listOfList.add(list2);

        // It will get the second list from the list of list
        // Then get the last element of that list
        System.out.println(
                listOfList.get(1).get(list2.size() - 1)
        );


        System.out.println();
        /*******************************************************************************************/
        // List order after adding elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 18:");
        System.out.println("===========");


        // List doesn't replace the element in an index if any element exist
        // It shifts the elements back and insert the current element

        System.out.println("Elements before inserting: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();

        System.out.println("Size before inserting: " + list2.size());

        // Inserting at a index
        list2.add(9, "Asif");

        System.out.println("Size after inserting: " + list2.size());

        System.out.println("Elements After inserting: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // List order after removing elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 19:");
        System.out.println("===========");


        // On removal of an item from the list, items right to the removing item will shift back left
        // Also if the are multiple object with same value, remove will only remove one of them
        // Removing by index return the value at that index
        // Removing by value return true if the value is found otherwise false

        System.out.println("Elements before removing: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();

        System.out.println("Size before removing: " + list2.size());

        // removing by object
        boolean found = list2.remove("Asif");
        System.out.println("Element to remove found? : " + found);

        // removing by index
        String itemRemovedByIndex = list2.remove(1);
        System.out.println("Item removed by index: " + itemRemovedByIndex);


        System.out.println("Size after removing: " + list2.size());

        System.out.println("Elements After removing: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // List order after removing elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 20:");
        System.out.println("===========");

        // Nothing yet
    }
}

One thought on “Java Collections Generics List and ArrayList Methods Usage tutorial

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s