How to get sublist from a list in Java [Practical Examples]


Deepak Prasad

Java Examples

How to get sublist from a list in Java

In Java, ArrayList is a re-sizable array implementation of the List interface present in java.util package. Whereas, LinkedList is a doubly linked list implementation of the List interface present in java.util package. In order to get sublist either in an ArrayList or LinkedList, we have to use the sublist() method which is a method of AbstractList class.

 

Syntax

The statement below shows the syntax of sublist method.

This method returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. However, it will throw an IndexOutOfBoundsException if the index value is out of range on either side. Similarly, it will throw an IllegalArgumentException if the fromindex is greater than toindex value.

list.sublist(fromindex, toindex);

 

Examples to get sublist in Java

The examples below shows different usages of sublist method in Java.

 

Example 1: Get sublist from ArrayList

In this example, we are taking an ArrayList of Integer type and adding the values to it using the add() method. Thereafter, we will use sublist method to get sublist of the given list.

// Program to get sublist from a list in Java
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {

        // ArrayList Declaration          
        ArrayList a = new ArrayList();

        // Adding the values
        a.add(11);
        a.add(14);
        a.add(91);
        a.add(215);
        a.add(36);

        // Print original arraylist
        System.out.println("Original List : " + a);

        // Print the subList 
        System.out.println("Sublist of original list from index 2 to 4: " + a.subList(2, 4));
    }
}

Output

Original List : [11, 14, 91, 215, 36]
Sublist of original list from index 2 to 4: [91, 215]

 

Example 2: Get a sublist from LinkedList

In this example, we are taking a LinkedList of Integer type and adding the values to it using the add() method. Thereafter, we will use sublist method to get sublist of the given list.

// Program to get sublist from a list in Java
import java.util.LinkedList;
public class Main {
    public static void main(String[] args) {

        // LinkedList Declaration          
        LinkedList a = new LinkedList();

        // Adding the values
        a.add(11);
        a.add(14);
        a.add(91);
        a.add(215);
        a.add(36);

        // Print original LinkedList
        System.out.println("Original List : " + a);

        // Print the subList 
        System.out.println("Sublist of original list from index 2 to 4: " + a.subList(2, 4));
    }
}

Output

Original List : [11, 14, 91, 215, 36]
Sublist of original list from index 2 to 4: [91, 215]

 

Example 3: Remove sublist from a LinkedList

In this example, we are taking a LinkedList of Character type and adding the alphabets to it using the add() method. Thereafter, we will use sublist method and clear method to remove some values from the list.

// Program to get and remove the sublist from a list in Java
import java.util.LinkedList;
public class Main {
    public static void main(String[] args) {
        // LinkedList Declaration          
        LinkedList a = new LinkedList();

        // Adding the values
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            a.add(ch);
        }
        // Print original LinkedList
        System.out.println("Original List : " + a);

        a.subList(7, 19).clear();
        // Print the subList 
        System.out.println("Now the list after removing 7 to 19 is " + a);
    }

}

Output

Original List : [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
Now the list after removing 7 to 19 is [A, B, C, D, E, F, G, T, U, V, W, X, Y, Z]

 

Example 4: Get sublist of prime numbers

In this example, we are taking a LinkedList of Integer type and adding the prime numbers in the range of 1 to 50 to it using the add() method. Thereafter, we will use sublist method to get the prime numbers stored from index 5 to 10

// Program to get sublist from a list in Java
import java.util.LinkedList;
public class Main {
    public static void main(String[] args) {

        // LinkedList Declaration          
        LinkedList a = new LinkedList();

        int i = 0;
        int num = 0;
        for (i = 1; i <= 50; i++) {
            int counter = 0;
            for (num = i; num >= 1; num--) {
                if (i % num == 0) {
                    counter = counter + 1;
                }
            }
            if (counter == 2) {
                //Appended the Prime number to the list
                a.add(i);
            }
        }
        // Print original LinkedList
        System.out.println("Prime numbers between 1 to 50 : " + a);

        // Print the subList 
        System.out.println("Sublist of original list from index 5 to 10: " + a.subList(5, 10));
    }
}

Output

Original List : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sublist of original list from index 2 to 4: [13, 17, 19, 23, 29]

 

Example 5: Get sublist of city

In this example, we are taking a ArrayList of String type and adding the city names to it using the add() method. Thereafter, we will use sublist method to get names of cities from 2 to last value.

// Program to get sublist from a list in Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        // ArrayList Declaration          
        ArrayList a = new ArrayList();

        a.add("Delhi");
        a.add("Mumbai");
        a.add("Chennai");
        a.add("Hyderabad");
        a.add("Bengaluru");
        // Print original ArrayList
        System.out.println("Original List : " + a);

        // Print the subList 
        System.out.println("Sublist of original list from index 2 to 4: " + a.subList(2, a.size()));
    }
}

Output

Original List : [Delhi, Mumbai, Chennai, Hyderabad, Bengaluru]
Sublist of original list from index 2 to 4: [Chennai, Hyderabad, Bengaluru]

 

Example 6: Divide the list into 4 equal parts using sublist

In this example, we are taking a ArrayList of Integer type and adding the registration number of 40 students to it using the add() method. Thereafter, we will divide this students equally into 4 different batches using the sublist method and size() method.

// Program to get sublist from a list in Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        // ArrayList Declaration          
        ArrayList a = new ArrayList();

        for (int i = 1001; i <= 1040; i++) {
            a.add(i);
        }
        // Print original ArrayList
        System.out.println("Registration number of all students : " + a);

        // Print the subList 
        System.out.println("\n Dividing students batch wise");
        System.out.println("Batch A :" + a.subList(0, a.size() / 4));
        System.out.println("Batch B :" + a.subList((a.size() / 4), a.size() / 2));
        System.out.println("Batch C :" + a.subList((a.size() / 2), (a.size() * 3) / 4));
        System.out.println("Batch D :" + a.subList((a.size() * 3) / 4, a.size()));
    }

}

Output

Registration number of all students : [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040]

 Dividing students batch wise
Batch A :[1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]
Batch B :[1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020]
Batch C :[1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030]
Batch D :[1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040]

 

Summary

The knowledge of getting the sublist from a list in Java is very useful while working on real time applications. In this tutorial, we covered the different scenario to get sublist from an ArrayList and LinkedList with an example. As per the requirement of an application, we can choose an appropriate approach for getting the sublist. We learned in detail about sublist with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on get a sublist from a list in Java.

 

References

ArrayList Class
LinkedList Class

 

Views: 3

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel