w3resource

Java: Extract a portion of a array list


12. Extract Sublist from ArrayList

Write a Java program to extract a portion of an array list.

Pictorial Presentation:

Java Collection, ArrayList Exercises: Extract a portion of a list

Sample Solution:-

Java Code:

import java.util.*;
  public class Exercise12 {
  public static void main(String[] args) {
  // Creae a list and add some colors to the list
  List<String> list_Strings = new ArrayList<String>();
  list_Strings.add("Red");
  list_Strings.add("Green");
  list_Strings.add("Orange");
  list_Strings.add("White");
  list_Strings.add("Black");
  System.out.println("Original list: " + list_Strings);
  List<String> sub_List = list_Strings.subList(0, 3);
  System.out.println("List of first three elements: " + sub_List);
 }
}

Sample Output:

Original list: [Red, Green, Orange, White, Black]                      
List of first three elements: [Red, Green, Orange]

Flowchart:

Flowchart: Extract a portion of a list.

For more Practice: Solve these Related Problems:

  • Write a Java program to extract a sublist from an ArrayList using subList() and then print the sublist.
  • Write a Java program to extract the first half of an ArrayList and then merge it with the second half reversed.
  • Write a Java program to create a new ArrayList containing elements from a specified start index to an end index using streams.
  • Write a Java program to remove a range of elements from an ArrayList and print the remaining list.

Go to:


PREV : Reverse ArrayList.
NEXT : Compare Two ArrayLists.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.