📜  Java番石榴 |带有示例的 Lists.partition() 方法

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

Java番石榴 |带有示例的 Lists.partition() 方法

Guava 库中的Lists.partition()方法用于将原始列表划分为相同大小的子列表。该方法接受两个参数。

例如:如果作为参数传递的原始列表为 [a, b, c, d, e] 并且分区大小为 3,则子列表产量为 [[a, b, c], [d, e]] .

句法:

参数:该方法接受两个参数:

  • list:根据分区大小划分为子列表的列表。
  • size:每个子列表的所需大小。最后一个子列表的大小可能会更小。

返回值:该方法返回连续子列表的列表。每个子列表(可能最后一个除外)的大小等于分区大小。

异常:如果分区大小为非正数,则Lists.partition()方法将引发IllegalArgumentException

下面的例子说明了上述方法的实现:

示例 1:

// Java code to show implementation of
// Guava's Lists.partition() method
  
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // Creating a List of Integers
        List myList
            = Arrays.asList(1, 2, 3, 4, 5);
  
        // Using Lists.partition() method to divide
        // the original list into sublists of the same
        // size, which are just views of the original list.
        // The final list may be smaller.
        List > lists
            = Lists.partition(myList, 2);
  
        // Displaying the sublists
        for (List sublist: lists)
            System.out.println(sublist);
    }
}
输出:
[1, 2]
[3, 4]
[5]

示例 2:

// Java code to show implementation of
// Guava's Lists.partition() method
  
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a List of Characters
        List myList
            = Arrays.asList('H', 'E', 'L', 'L', 'O',
                            'G', 'E', 'E', 'K', 'S');
  
        // Using Lists.partition() method to divide
        // the original list into sublists of the same
        // size, which are just views of the original list.
        // The final list may be smaller.
        List > lists
            = Lists.partition(myList, 3);
  
        // Displaying the sublists
        for (List sublist: lists)
            System.out.println(sublist);
    }
}
输出:
[H, E, L]
[L, O, G]
[E, E, K]
[S]

参考: https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-