Split / Partition a collection into smaller collections - Java - Tutorial

Partition a collection into smaller collections

This article describes how to partition a collections into a given number of smaller collections.


Table of Contents

1. Partition a collection
2. Partition collection in Java
2.1. Implementation
2.2. Test
3. About this website
3.1.
4. Links and Literature
4.1. Source Code
4.2. General

1. Partition a collection

Sometime you want split a collection into smaller collections. The following gives an example how to do this.

Tip

Please note that this example is an adjusted example of the Google collection and more or less the same as Code Ranch discussion The Google source code can be found here Original source code

The test code also demonstrate how to calculate the number of elements which should go into one bucket in case you want to have a fixed number of buckets.

2. Partition collection in Java

2.1. Implementation

Create a Java project "de.vogella.algorithms.partitioncollection".

Create the following program.

package de.vogella.algorithms.partitioncollection;

import java.util.AbstractList;
import java.util.List;

public class MyPartition {
/** * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, * each of the same size (the final list may be smaller). For example, * partitioning a list containing {@code [a, b, c, d, e]} with a partition * size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing * two inner lists of three and two elements, all in the original order. * * <p>The outer list is unmodifiable, but reflects the latest state of the * source list. The inner lists are sublist views of the original list, * produced on demand using {@link List#subList(int, int)}, and are subject * to all the usual caveats about modification as explained in that API. * * * Adapted from http://code.google.com/p/google-collections/ * * @param list the list to return consecutive sublists of * @param size the desired size of each sublist (the last may be * smaller) * @return a list of consecutive sublists * @throws IllegalArgumentException if {@code partitionSize} is nonpositive * */

    public static <T> List<List<T>> partition(List<T> list, int size) {

     if (list == null)
        throw new NullPointerException("‘list‘ must not be null");
      if (!(size > 0))
        throw new IllegalArgumentException("‘size‘ must be greater than 0");

      return new Partition<T>(list, size);
    }

    private static class Partition<T> extends AbstractList<List<T>> {

      final List<T> list;
      final int size;

      Partition(List<T> list, int size) {
        this.list = list;
        this.size = size;
      }

      @Override
      public List<T> get(int index) {
        int listSize = size();
        if (listSize < 0)
          throw new IllegalArgumentException("negative size: " + listSize);
        if (index < 0)
          throw new IndexOutOfBoundsException("index " + index + " must not be negative");
        if (index >= listSize)
          throw new IndexOutOfBoundsException("index " + index + " must be less than size " + listSize);
        int start = index * size;
        int end = Math.min(start + size, list.size());
        return list.subList(start, end);
      }

      @Override
      public int size() {
        return (list.size() + size - 1) / size;
      }

      @Override
      public boolean isEmpty() {
        return list.isEmpty();
      }
    }

}

  

2.2. Test

You can use the following JUnit test to validate the result.

package de.vogella.algorithms.partitioncollection;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class MyPartitionTest {
  @Test
  public void partitiontest1() {
    List<String> list = new ArrayList<String>();
    list.add("one");
    list.add("two");
    list.add("three");
    list.add("four");
    list.add("five");
    list.add("six");
    list.add("seven");
    list.add("eight");
    list.add("nine");
    list.add("ten");
    list.add("eleven");
    List<List<String>> partition = MyPartition.partition(list, 1);
    System.out.println(partition.get(2).size());
    assertTrue(partition.size()==11);
    assertTrue(partition.get(0).size()==1);
    partition = MyPartition.partition(list, 7);
    assertTrue(partition.size()==2);
    assertTrue(partition.get(0).size()==7);
    assertTrue(partition.get(1).size()==4);

    // now let assume you want to have x number of buckets
    // How many elements must placed in a list?
    // Take x as 3

    int buckets = 3;
    int divide = list.size() / buckets;
    if (list.size() % buckets !=0){
      divide ++;
    }
    System.out.println("Max. number of element in each bucket " + divide);
    partition = MyPartition.partition(list, divide);
    assertTrue(partition.size()==buckets);
  }
}

  

时间: 2024-10-04 13:12:59

Split / Partition a collection into smaller collections - Java - Tutorial的相关文章

oracle中add&amp;split partition对global&amp;local index的影响

生产库中某些大表的分区异常,需要对现有表进行在线操作,以添加丢失分区,因为是生产库,还是谨慎点好,今天有空,针对add&split分区对global&local索引的影响进行了测试,测试版本为oracle11.2.0.4,过程如下: 首先,创建分区表: CREATE TABLE TP1 ( C1 INT PRIMARY KEY, C2 VARCHAR2(10), C3 CHAR(10) ) partition by range (c1) ( partition p1 values less

split partition用法

当分区表有最大分区的时候,不能直接添加分区,就需要用到split partition: 下面是示例: create table a (id number, name varchar2(30),name1 varchar2(30),name2 varchar2(30),time date) partition by range (time)( partition p2013 values less than (to_date('2014-01-01', 'yyyy-mm-dd')), partit

I学霸官方免费教程三十五:Java集合框架之Collection接口和Collections类

Collection接口 Collection接口是List和Set接口的父接口,其中主要定义了一些集合基本操作的方法,包括与Iterator之间的关系List  extends  CollectionArrayList  implements  ListLinkedList  implements  ListVector  implements  ListSet  extends  CollectionHashSet  implements  SetSortedSet  extends  Se

Summary: Arrays vs. Collections &amp;&amp; The differences between Collection Interface and Collections Class

转自http://www.anylogic.com/anylogic/help/index.jsp?topic=/com.xj.anylogic.help/html/code/Arrays_Collections.html Java offers two types of constructs where you can store multiple values or objects of the same type: arrays and collections (for System Dy

Collection接口和Collections类的简单区别和讲解

这里仅仅进行一些简单的比较,如果你想要更加详细的信息话,请自己百度. 1.Collection: 是集合类的上层接口.本身是一个Interface,里面包含了一些集合的基本操作. Collection接口时Set接口和List接口的父接口 里面的常用操作有如下内容: 2.Collections Collections是一个集合框架的帮助类,里面包含一些对集合的排序,搜索以及序列化的操作. 最根本的是Collections是一个类哦. 下面是Collections类中的常用操作: 好吧,就先到这里

模拟java的split函数,分割字符串,类似于java的split方法

/*自定义oracle的分割函数*//*定义一个type,用户接收返回的数据集合*/create or replace type splitType as table of varchar2(4000); /* 参数1: 被分割的字符串 参数2:分割字符串,默认是英文逗号*/create or replace function split_str(str varchar2, split_char varchar2:=',') return splitType pipelinedis idx nu

How to implement common datastructures (List, Stack, Map) in plain Java - Tutorial

List, Map and Stack implementations in Java This article describes how to implement data structures (List Stack, Map) in Java. The implementations in this articles are for demonstration and education purpose. They do not try to be as efficient as the

How to implement an ArrayList structure in Java - Tutorial

List implementations in Java This article describes how to implement a list data structure in Java. The implementations in this articles are for demonstration and education purpose. They do not try to be as efficient as the standard libraries and the

Java Tutorial

http://www.tutorialspoint.com/java/index.htm