Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Remove a Sublist from a List
In this article, we will understand how to remove a sub-list from a list. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.
Below is a demonstration of the same −
Suppose our input is −
Input list: [Java, Programming, Is, Fun]
The desired output would be −
The list after removing a sublist is: [Java, Programming]
Algorithm
Step 1 - START Step 2 - Declare an AbstractList namely input_list. Step 3 - Add the values to the list. Step 4 - Use subList().clear() to clear the sublist from the specified index values. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*;
public class Demo {
public static void main(String args[]){
AbstractList<String> input_list = new LinkedList<String>();
input_list.add("Java");
input_list.add("Programming");
input_list.add("Is");
input_list.add("Fun");
System.out.println("The list is defined as: " + input_list);
input_list.subList(2, 4).clear();
System.out.println("The list after removing a sublist is: " + input_list);
}
}
Output
The list is defined as: [Java, Programming, Is, Fun] The list after removing a sublist is: [Java, Programming]
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*;
public class Demo {
static void remove_sublist(AbstractList input_list){
input_list.subList(2, 4).clear();
System.out.println("The list after removing a sublist is: " + input_list);
}
public static void main(String args[]){
AbstractList<String> input_list = new LinkedList<String>();
input_list.add("Java");
input_list.add("Programming");
input_list.add("Is");
input_list.add("Fun");
System.out.println("The list is defined as: " + input_list);
remove_sublist(input_list);
}
}
Output
The list is defined as: [Java, Programming, Is, Fun] The list after removing a sublist is: [Java, Programming]
Advertisements