Java 把一个列表分成两半

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. 使用循环(Naive Approach)。
  2. 使用List类的subList()方法
  3. 使用收集器类的partitioningBy()方法
  4. 使用Google guava库

让我们来讨论一下上述定义的方法的细节,并通过干净的java程序来实现,如下所示。

方法1: 使用循环

方法

  1. 创建两个新的空列表,并将原始列表的前一半元素。
  2. 重置到第二个空列表中。

例子

// 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]

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

它返回该列表中从指定索引(include)到另一个索引(exclude)之间的部分的视图。例如,让我们任意地从2到5,这里的索引2将只包括。如果两个指定的索引相等,返回的列表是空的。List.subList()返回的是一个列表,所以返回的列表没有结构性变化。

例子

// 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]

方法3: 使用收集器类的partitioningBy()方法

Java 8 Collectors.partitioningBy()是一个将流的元素总是分成两部分的方法,与Naive和List.subList()不同。它返回一个收集器,该收集器将值存储在一个Map中。该地图的键只能是布尔值。

语法: partitioningBy()方法

public static  Collector<T, ?, Map<Boolean, List>> 
partitioningBy(Predicate predicate)

例子

// 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]

方法4: 使用Google guava库

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

例子

// 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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程