Friday, September 29, 2023

10 Example of List in Java

Hello guys,  Java, as a versatile and widely used programming language, offers a plethora of data structures to developers. One of them is List which is also fundamental component in Java's collection framework, play a pivotal role in managing and manipulating sequences of elements. In the past, I have shared 10 Examples of HashMap in Java and In this article, we'll delve into Java lists, exploring their features and providing ten illustrative examples to deepen your understanding. List are also a popular topic from Java interviews with questions like difference between ArrayList and LinkedList which have been asked to me almost 10 times in past 20 years. 


What is a List in Java?

A List in Java is an ordered collection that allows elements to be inserted, accessed, and removed based on their position in the list. The List interface is a part of the Java Collections Framework, providing a set of methods for working with lists. 

n Java, a List is an interface that belongs to the Java Collections Framework. It's part of the java.util package, and it extends the Collection interface. Two commonly used classes that implement the List interface are ArrayList and LinkedList.

The key characteristics of a List in Java include:

Ordered Collection
A List maintains the order of elements in which they are inserted. This means you can iterate through a List to access elements in a specific sequence.

Index-Based Access
Elements in a List can be accessed using an index. The index starts from 0 for the first element, 1 for the second, and so on.

Allows Duplicates
Unlike some other collection types, a List allows duplicate elements. Each element in a List has a distinct index.

Dynamic Size
A List can dynamically grow or shrink in size. You can add or remove elements, and the List will handle the resizing internally.

The List interface declares various methods that enable you to perform operations such as adding, removing, and retrieving elements. Some of the common methods include add, get, remove, size, indexOf, contains, and more.


10 Example of List and ArrayList in Java



10 Examples of List and ArrayList in Java

Now that we know what is List, let's see 10 example of List in Java. We will use ArrayList as a class for all examples:

Example 1: Creating an ArrayList

Let's start with a basic example of creating an ArrayList in Java:

import java.util.ArrayList;

import java.util.List;



public class Example1 {

    public static void main(String[] args) {

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

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Orange");



        System.out.println("Fruits: " + fruits);

    }

}

In this example, we create an ArrayList called fruits, add three elements to it, and print the contents. 

The output will be: Fruits: [Apple, Banana, Orange].


Example 2: Iterating Through a List

Java provides multiple ways to iterate through a list. Here's an example using the enhanced for loop:

import java.util.ArrayList;

import java.util.List;



public class Example2 {

    public static void main(String[] args) {

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

        colors.add("Red");

        colors.add("Green");

        colors.add("Blue");



        // Using enhanced for loop

        for (String color : colors) {

            System.out.println(color);

        }

    }

}

This code will print each color on a new line.


Example 3: Checking if a List Contains an Element

You can easily check if a list contains a specific element using the contains() method as shown in following example:


import java.util.ArrayList;

import java.util.List;



public class Example3 {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        numbers.add(10);

        numbers.add(20);

        numbers.add(30);



        // Check if the list contains a specific number

        if (numbers.contains(20)) {

            System.out.println("The list contains 20.");

        } else {

            System.out.println("The list does not contain 20.");

        }

    }

}


Example 4: Removing Elements from a List

Removing elements from a list can be achieved using the remove method. Let's remove an element by value and by index:

import java.util.ArrayList;

import java.util.List;



public class Example4 {

    public static void main(String[] args) {

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

        books.add("Java Fundamentals");

        books.add("Data Structures and Algorithms");

        books.add("Design Patterns");


        // Remove by value

        books.remove("Data Structures and Algorithms");

        // Remove by index

        books.remove(0);

        System.out.println("Remaining books: " + books);

    }

}



Example 5: Sorting a List

Sorting a list can be done using the Collections.sort()  method as shown below but you can also use List.sort() method to sort a List in Java. 

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;



public class Example5 {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        numbers.add(40);

        numbers.add(10);

        numbers.add(30);


        // Sorting the list

        Collections.sort(numbers);

        System.out.println("Sorted numbers: " + numbers);

    }

}


This example will print the numbers in ascending order.


Example 6: Sublist Operations

You can extract a sublist from a list using the subList method as shown below:

import java.util.ArrayList;

import java.util.List;



public class Example6 {

    public static void main(String[] args) {

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

        daysOfWeek.add("Monday");

        daysOfWeek.add("Tuesday");

        daysOfWeek.add("Wednesday");

        daysOfWeek.add("Thursday");

        daysOfWeek.add("Friday");

        daysOfWeek.add("Saturday");

        daysOfWeek.add("Sunday");


        // Extracting a sublist

        List<String> workdays = daysOfWeek.subList(0, 5);


        System.out.println("Workdays: " + workdays);

    }

}


Example 7: Merging Lists

You can merge two lists using the addAll() method as shown below:

import java.util.ArrayList;

import java.util.List;



public class Example7 {

    public static void main(String[] args) {

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

        list1.add("A");

        list1.add("B");



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

        list2.add("C");

        list2.add("D");


        // Merging lists

        list1.addAll(list2);

        System.out.println("Merged list: " + list1);

    }

}


Example 8: Finding the Size of a List

To determine the size of a list, use the size() method as shown in following example:

import java.util.ArrayList;

import java.util.List;



public class Example8 {

    public static void main(String[] args) {

        List<Double> temperatures = new ArrayList<>();

        temperatures.add(25.5);

        temperatures.add(28.0);

        temperatures.add(22.8);


        // Finding the size of the list

        int size = temperatures.size();

        System.out.println("Number of temperatures: " + size);

    }

}


Example 9: Clearing a List

To remove all elements from a list, use the clear()  method as shown below:

import java.util.ArrayList;

import java.util.List;



public class Example9 {

    public static void main(String[] args) {

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

        cities.add("New York");

        cities.add("London");

        cities.add("Tokyo");


        // Clearing the list

        cities.clear();

        System.out.println("Cities after clearing: " + cities);

    }

}


Example 10: Converting List to Array

You can convert a list to an array using the toArray method:

import java.util.ArrayList;

import java.util.List;



public class Example10 {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        numbers.add(5);

        numbers.add(10);

        numbers.add(15);



        // Converting list to array

        Integer[] array = numbers.toArray(new Integer[0]);



        // Printing the array

        for (int num : array) {

            System.out.println(num);

        }

    }

}

Conclusion

That's all in this 10 examples of List in Java. In this comprehensive exploration of Java lists, we've covered fundamental operations and provided practical examples to guide you through their implementation. Understanding how to manipulate lists is crucial for efficient Java programming, especially in scenarios involving dynamic data management

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.