Here we are given a list and the task is to split it into two news lists as one can better perceive from the below illustration as follows:
Illustration:
Input : list = {1, 2, 3, 4, 5, 6} Output : first = {1, 2, 3}, second = {4, 5, 6} Input : list = {1, 2, 3, 4, 5} Output : first = {1, 2}, second = {3, 4, 5}
Methods:Â
- Using loops(Naive Approach)
- Using subList() method of List class
- Using partitioningBy() method of Collectors class
- Using Google guava Library
Let us do discuss the above-defined methods to details alongside implementing via clean java programs as follows:
Method 1: Using loops
Approach:
- Create two new empty lists and assign the first half element of the original list.
- Reset into the second empty list.
Example:
Java
// Java Program to Split a List into Two Sublist Â
// Importing required classes import java.util.ArrayList; import java.util.List; Â
// Main class public class GFG { Â
    // Method 1     // To split a list into two sublists in Java     public static List[] split(List<String> list)     { Â
        // Creating two empty lists         List<String> first = new ArrayList<String>();         List<String> second = new ArrayList<String>(); Â
        // Getting size of the list         // using size() method         int size = list.size(); Â
        // Step 1         // (First size)/2 element copy into list         // first and rest second list         for ( int i = 0 ; i < size / 2 ; i++)             first.add(list.get(i)); Â
        // Step 2         // (Second size)/2 element copy into list first and         // rest second list         for ( int i = size / 2 ; i < size; i++)             second.add(list.get(i)); Â
        // Returning a List of array         return new List[] { first, second };     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     { Â
        // Creating an ArrayList of string type         List<String> list = new ArrayList<String>(); Â
        // Adding elements to list object         // using add() method         list.add( "Geeks" );         list.add( "Practice" );         list.add( "Contribute" );         list.add( "IDE" );         list.add( "Courses" ); Â
        // Calling split method which return List of array         List[] lists = split(list); Â
        // Printing specific elements of list by         // passing arguments with in         System.out.println(lists[ 0 ]);         System.out.println(lists[ 1 ]);     } } |
[Geeks, Practice] [Contribute, IDE, Courses]
Method 2: Using subList() method of List class
It returns a view of the portion of this list between the specified index(include) to another index (exclude). For example, let us take arbitrarily from 2 to 5, Here index 2 will include only. In case if both specified indexes are equal, the returned list is empty. The List.subList() returned a list, so non-structural changes in the returned list.
Example:
Java
// Java Program to Split a List into Two SubList // Using subList() method of List class Â
// Importing required classes import java.util.ArrayList; import java.util.List; Â
// Main class public class GFG { Â
    // Method 1     // To split a list into two sublists in Java     public static List[] split(List<String> list)     { Â
        // Finding the size of the list using List.size()         // and putting in a variable         int size = list.size(); Â
        // Creating new list and inserting values which is         // returned by List.subList() method         List<String> first             = new ArrayList<>(list.subList( 0 , (size) / 2 ));         List<String> second = new ArrayList<>(             list.subList((size) / 2 , size)); Â
        // Returning an List of array         return new List[] { first, second };     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     { Â
        // Creatingan ArrayList of String type         List<String> list = new ArrayList<String>(); Â
        // Adding elements to List object         // Custom input elements         list.add( "Geeks" );         list.add( "Practice" );         list.add( "Contribute" );         list.add( "IDE" );         list.add( "Courses" ); Â
        // Calling split method which return List of array         List[] lists = split(list); Â
        // Printing specific elements of list by         // passing arguments with in         System.out.println(lists[ 0 ]);         System.out.println(lists[ 1 ]);     } } |
[Geeks, Practice] [Contribute, IDE, Courses]
Method 3: Using partitioningBy() method of Collectors classÂ
Java 8 Collectors.partitioningBy() is a method that partitions the elements of stream always in two-part, unlike Naive and List.subList(). It returns a Collector that stores the values in a Map. The key of the map can be only in Boolean.
Syntax: partitioningBy() methodÂ
public static Collector<T, ?, Map<Boolean, List>> partitioningBy(Predicate predicate)
Example:
Java
// Java Program to Split a List into Two Sub-List /// Using partitioningBy() method of Collectors class Â
// Importing required classes import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; Â
// Main class public class GFG { Â
    // Method 1     // To split a list into two sublists in Java     public static List[] split(List<String> list)     { Â
        // Setting value of midIndex using comparators         int midIndex             = ((list.size() / 2 )                - (((list.size() % 2 ) > 0 ) ? 0 : 1 )); Â
        // Creating object of List with reference to         // ArrayList class Declaring object List<String>         // type         List<List<String> > lists = new ArrayList<>(             list.stream()                 .collect(Collectors.partitioningBy(                     s -> list.indexOf(s) > midIndex))                 .values()); Â
        // Returning an array containing both lists         return new List[] { lists.get( 0 ), lists.get( 1 ) };     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     { Â
        // Creating an ArrayList of String type         List<String> list = new ArrayList<String>(); Â
        // Adding elements to List object         // Using add() method         list.add( "Geeks" );         list.add( "Practice" );         list.add( "Contribute" );         list.add( "IDE" );         list.add( "Courses" ); Â
        // Calling split method which return List of array         List[] lists = split(list); Â
        // Printing specific elements of list by         // passing arguments with in         System.out.println(lists[ 0 ]);         System.out.println(lists[ 1 ]);     } } |
[Geeks, Practice, Contribute] [IDE, Courses]
Method 4: Using Google guava Library Â
Guava is an open-source Java-based library which is developed by Google Inc. In the Guava library, we can use Lists.partition() method that splits the list into consecutive sublists, every list specified size. In order to split the list into two sublists, In our case, we can pass the size that is equal to half the size of our list.
ExampleÂ
Java
// Java Program to Split a List into Two Sub-List Â
// Importing Guava library import com.google.common.collect.Iterables; // Importing required classes import java.util.ArrayList; import java.util.Iterator; import java.util.List; Â
// Main class public class GFG { Â
    // Method 1     // To split a list into two sublists in Java     public static List[] split(List<String> list)     { Â
        // Partition the List into two sublists and         // getting iterator         Iterator<List<String> > itr             = Iterables.partition(list, (list.size()) / 2 )                   .iterator(); Â
        // Returning an array containing both lists         return new List[] { new ArrayList<>(itr.next()),                             new ArrayList<>(itr.next()) };     } Â
    // Method 2     // Main driver method     public static void main(String[] args)     { Â
        // Creating an ArrayList of string type         List<String> list = new ArrayList<String>(); Â
        // Adding elements t oabove object         // Custom input elements         list.add( "Geeks" );         list.add( "Practice" );         list.add( "Contribute" );         list.add( "IDE" );         list.add( "Courses" ); Â
        // Calling split method which return List of array         List[] lists = split(list); Â
        // Printing specific elements of list by         // passing arguments with in         System.out.println(lists[ 0 ]);         System.out.println(lists[ 1 ]);     } } |
[Geeks, Practice] [Contribute, IDE]