📌  相关文章
📜  在Java中将列表分成两半

📅  最后修改于: 2022-05-13 01:55:44.702000             🧑  作者: Mango

在Java中将列表分成两半

这里给了我们一个列表,任务是将它分成两个新闻列表,从下图可以更好地理解如下:

插图:

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}

方法:

  1. 使用循环(朴素方法)
  2. 使用 List 类的 subList() 方法
  3. 使用 Collectors 类的 partitioningBy() 方法
  4. 使用谷歌番石榴库

让我们在通过干净的Java程序实现的同时详细讨论上面定义的方法,如下所示:

方法一:使用循环

方法:

  1. 创建两个新的空列表并分配原始列表的前半部分元素。
  2. 重置为第二个空列表。

例子:

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 list)
    {
 
        // Creating two empty lists
        List first = new ArrayList();
        List second = new ArrayList();
 
        // 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 list = new ArrayList();
 
        // 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]);
    }
}


Java
// Java Program to Split a List into Two SubList
// Using subList() method of List clas
 
// 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 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 first
            = new ArrayList<>(list.subList(0, (size) / 2));
        List 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 list = new ArrayList();
 
        // 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]);
    }
}


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 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
        // type
        List > 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 list = new ArrayList();
 
        // 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]);
    }
}


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 list)
    {
 
        // Partition the List into two sublists and
        // getting iterator
        Iterator > 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 list = new ArrayList();
 
        // 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, Courses]

方法二:使用 List 类的 subList() 方法

它返回此列表在指定索引(包括)到另一个索引(排除)之间的部分的视图。例如,让我们从 2 到 5 任意取,这里索引 2 将只包括。如果两个指定的索引相等,则返回的列表为空。 List.subList() 返回一个列表,因此返回列表中的非结构性变化。

例子:

Java

// Java Program to Split a List into Two SubList
// Using subList() method of List clas
 
// 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 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 first
            = new ArrayList<>(list.subList(0, (size) / 2));
        List 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 list = new ArrayList();
 
        // 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]

方法三:使用 Collectors 类的 partitioningBy() 方法

Java 8 Collectors.partitioningBy() 是一种始终将流元素划分为两部分的方法,这与 Naive 和 List.subList() 不同。它返回一个将值存储在 Map 中的 Collector。地图的键只能是布尔值。

语法: partitioningBy() 方法

public static  Collector> 
partitioningBy(Predicate predicate)

例子:

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 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
        // type
        List > 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 list = new ArrayList();
 
        // 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]

方法四:使用谷歌番石榴库  

Guava 是由 Google Inc. 开发的基于 Java 的开源库。在 Guava 库中,我们可以使用 Lists.partition() 方法将列表拆分为连续的子列表,每个列表指定大小。为了将列表拆分为两个子列表,在我们的例子中,我们可以传递等于列表一半大小的大小。

例子

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 list)
    {
 
        // Partition the List into two sublists and
        // getting iterator
        Iterator > 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 list = new ArrayList();
 
        // 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]