Split a List into Two Halves in Java
Last Updated : 10 Aug, 2022
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]); } }
Output[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]); } }
Output[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]); } }
Output[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]); } }
Output[Geeks, Practice] [Contribute, IDE]
Similar Reads
Java List Interface The List Interface in Java extends the Collection Interface and is a part of the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features:Maintained the order of elements in which they are added.Allows
15+ min read
AbstractList in Java with Examples The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. AbstractList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Rand
7 min read
ArrayList in Java Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
LinkedList in Java Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure, which is a linear data structure where the elements are not stored in contiguous locations, and every element is a separate object with a data part and an
12 min read
Immutable List in Java ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An I
5 min read
CopyOnWriteArrayList in Java CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to b
6 min read
Custom ArrayList in Java Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection
8 min read
Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection As we know that the ArrayList is not synchronized, if multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. Hence synchronizing the ArrayList is a must to achieve thread safety in a multi-threaded environment. In order to make List objects we
6 min read
How to remove a SubList from a List in Java Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user. Example: Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4 Output [1, 2, 5, 6, 7, 8] Input
2 min read
Randomly Select Items from a List in Java In this article, we will explore how to efficiently select an element from a list in Java. The basic approach involves generating a random index between 0 and the size of the list, and then using that index to retrieve the item. Different Ways to Select Items from a ListBelow are the different appro
3 min read