Skip to main content

Java subList from ArrayList

How to get subList from ArrayList in Java?

In this article, we are going to learn how we can get a sublist from ArrayList in Java. By applying the starting and ending index, we can find a sublist from ArrayList. Also, we are going to see how to find a sublist in java based on some predicate.

If you are new to ArrayList, read this article first: All about ArrayList in Java.

Content of the Article


Java sublist by starting and ending index

The subList() method of ArrayList is used to find a sublist in java. This method returns a portion of an ArrayList based on the starting and ending index. Let's first look at the syntax of subList():
Syntax of subList()
List<T> subList = arrayList.subList(fromIndex, toIndex);
This method takes two integer arguments: fromIndex and toIndex as name suggests, fromIndex for starting index and toIndex for ending index. The toIndex is an exclusive type argument i.e., the element of ArrayList at toIndex location will not be included into the sublist.
Note : These index arguments can raise exception:
  • If fromIndex/toIndex are smaller than 0 or greater than the size of ArrayList then java.lang.IndexOutOfBoundException will be raised
  • If fromIndex > toIndex then java.lang.IllegalArgumentException will be raised.

Java sublist Example 1: Get sublist by starting and ending index

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                        Arrays.asList("Java", "C++", "NodeJS", "JavaScript", "Python"));
                System.out.println("Original ArrayList: " + languageList);

                ArrayList<String> languageSubList = subListByIndex(languageList, 1, 4);
                System.out.println("SubList By index: " + languageSubList);
        }
        private static <T> ArrayList<T> subListByIndex(ArrayList<T> arrayList,
           int fromIndex, int toIndex) {
                try {
                        // Java sublist from ArrayList
                        List<T> subList = arrayList.subList(fromIndex, toIndex);
                        return new ArrayList<>(subList);
                } catch (IndexOutOfBoundsException | IllegalArgumentException  ex) {
                        System.out.println("Exceoption due to: " + ex.getMessage());
                        return null;
                }
        }
}
Output
Original ArrayList: [Java, C++, NodeJS, JavaScript, Python]
SubList By index: [C++, NodeJS, JavaScript]

Java sublist by Predicate

Above we have learned, how to get the sublist by index but sometimes there can be the scenario that we want to get the sublist from the ArrayList based on some condition. From the ArrayList, we can create a sublist in java containing all elements that satisfy the given predicate. To do this, we can use the methods provided by the java stream API and Predicate Functional interface.
Let's look at the example:

Java sublist Example 2: Get sublist by Predicate

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                                Arrays.asList("Java", "C++", "NodeJS", "JavaScript", "Python"));
                System.out.println("Original ArrayList: " + languageList);

                // String Predicate that filter all language containing "J"
                Predicate<String> languagePredicate = (String language) -> language.contains("J");

                ArrayList<String> languageSubListByPredicate 
                                = subListByPredicate(languageList, languagePredicate);
                System.out.println("SubList By Predicate: " + languageSubListByPredicate);
        }
        private static <T> ArrayList<T> subListByPredicate(ArrayList<T> arrayList, 
             Predicate<T> predicate) {
                // Java sublist by predicate
                List<T> subList = arrayList.stream().filter(predicate)
                                        .collect(Collectors.toList());
                return new ArrayList<>(subList);
        }
}
Output
Original ArrayList: [Java, C++, NodeJS, JavaScript, Python]
SubList By Predicate: [Java, NodeJS, JavaScript]

Related Posts:


Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…