java 将list按照指定数量分成小list

11 篇文章 2 订阅

1、自己编写相关代码:

2、使用guava:

import java.util.ArrayList;  
import java.util.List;  
import com.google.common.collect.Lists;  
  
  
public class Test4 {  
  
    public static void main(String[] args) {  
        List<Long> list = new ArrayList<>();  
        list.add(1L);  
        list.add(2L);  
        list.add(3L);  
        list.add(4L);  
        list.add(5L);  
        list.add(6L);  
        list.add(7L);  
        list.add(8L);  
        list.add(9L);  
          
        //test1(list);  
        test2(list);  
    }  
      
    private static void test1(List<Long> list) {  
        int size = 2;  
        List<List<Long>> listArr = new ArrayList<>();    
          
        int arrSize = list.size()%size==0?list.size()/size:list.size()/size+1;    
        for(int i=0;i<arrSize;i++) {    
            List<Long>  sub = new ArrayList<>();    
            for(int j=i*size;j<=size*(i+1)-1;j++) {    
                if(j<=list.size()-1) {    
                    sub.add(list.get(j));    
                }    
            }    
            listArr.add(sub);    
        }    
        System.out.println(listArr.toString());  
    }  
      
      
    private static void test2(List<Long> list) {  
        int size = 16;  
        List<List<Long>> subSets = Lists.partition(list, size);    
        System.out.println(subSets.toString());  
    }  
}  

 

补充:guava分割其他collectionsiew plain

@Test    
public void givenCollection_whenParitioningIntoNSublists_thenCorrect() {    
    Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);    
     
    Iterable<List<Integer>> subSets = Iterables.partition(intCollection, 3);    
     
    List<Integer> firstPartition = subSets.iterator().next();    
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(1, 2, 3);    
    assertThat(firstPartition, equalTo(expectedLastPartition));    
}    

以上需要注意的是,partition返回的是原list的subview.视图,也即,原list改变后,partition之后的结果也会随着改变。

@Test    
public void givenListPartitioned_whenOriginalListIsModified_thenPartitionsChangeAsWell() {    
    // Given    
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);    
    List<List<Integer>> subSets = Lists.partition(intList, 3);    
     
    // When    
    intList.add(9);    
     
    // Then    
    List<Integer> lastPartition = subSets.get(2);    
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);    
    assertThat(lastPartition, equalTo(expectedLastPartition));    
}    


3、使用apache commons collection:

 

@Test    
public void givenList_whenParitioningIntoNSublists_thenCorrect() {    
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);    
    List<List<Integer>> subSets = ListUtils.partition(intList, 3);    
     
    List<Integer> lastPartition = subSets.get(2);    
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);    
    assertThat(subSets.size(), equalTo(3));    
    assertThat(lastPartition, equalTo(expectedLastPartition));    
}   

1.没有对应的Iterable.partions方法,类似guava那样

 

2.partition后的结果同样是原集合的视图。

 

4、Java8方法

 

1)通过grouping by:

@Test    
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {    
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);    
     
    Map<Integer, List<Integer>> groups =     
      intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));    
    List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());    
     
    List<Integer> lastPartition = subSets.get(2);    
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);    
    assertThat(subSets.size(), equalTo(3));    
    assertThat(lastPartition, equalTo(expectedLastPartition));    
}   

按年龄分组:

Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).    
 limit(100).    
 collect(Collectors.groupingBy(Person::getAge));    
Iterator it = personGroups.entrySet().iterator();    
while (it.hasNext()) {    
 Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();    
 System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());    
}    


2)通过partition by:

@Test  
public void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {  
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);  
   
    Map<Boolean, List<Integer>> groups =   
      intList.stream().collect(Collectors.partitioningBy(s -> s > 6));  
    List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());  
   
    List<Integer> lastPartition = subSets.get(1);  
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);  
    assertThat(subSets.size(), equalTo(2));  
    assertThat(lastPartition, equalTo(expectedLastPartition));  
}  

按照成年未成年人分组:

 

Map<Boolean, List<Person>> children = Stream.generate(new PersonSupplier()).  
 limit(100).  
 collect(Collectors.partitioningBy(p -> p.getAge() < 18));  
System.out.println("Children number: " + children.get(true).size());  
System.out.println("Adult number: " + children.get(false).size());  

注意:
1.Java8方式,分组后的list不再是原list的视图。所以,原list的改变不会影响分组后的结果。
2partitioningBy 其实是一种特殊的 groupingBy,它依照条件测试的是否两种结果来构造返回的数据结构,get(true) 和 get(false) 能即为全部的元素对象。
 

 

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 可以使用 Java 中的 sublist 方法将 List分成多个子 List。具体实现可以参考以下代码: ``` public static <T> List<List<T>> splitList(List<T> list, int size) { List<List<T>> result = new ArrayList<>(); int count = (list.size() + size - 1) / size; for (int i = ; i < count; i++) { int fromIndex = i * size; int toIndex = Math.min((i + 1) * size, list.size()); result.add(list.subList(fromIndex, toIndex)); } return result; } ``` 其中,list 表示要分割的 List,size 表示每个子 List 的大小。该方法返回一个 List,其中每个元素都是一个子 List。 ### 回答2: 在Java中,可以通过以下方式将List均分为多个子列表。 首先,确定每个子列表的大小,即每个子列表中元素的个数。可以通过计算List的大小除以子列表的个数来得到这个值。 然后,通过循环迭代的方式将List中的元素按照确定的每个子列表的大小进行分割。可以使用List的subList方法来截取对应大小的子列表。 下面是一个示例代码: ```java import java.util.ArrayList; import java.util.List; public class ListPartitioning { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); // 假设有一个大小为10的List for (int i = 1; i <= 10; i++) { list.add(i); } // 假设要将List分成3份 int partitionSize = list.size() / 3; List<List<Integer>> partitions = new ArrayList<>(); int fromIndex = 0; int toIndex = partitionSize; // 循环迭代分割List并添加到子列表中 for (int i = 0; i < 3; i++) { if (i == 2) { toIndex = list.size(); // 最后一份可能不够分,将toIndex设为List的末尾 } List<Integer> partition = list.subList(fromIndex, toIndex); partitions.add(partition); fromIndex = toIndex; toIndex += partitionSize; } // 打印结果 for (List<Integer> partition : partitions) { System.out.println(partition); } } } ``` 以上代码将一个大小为10的List均分为3个子列表,结果如下: [1, 2, 3] [4, 5, 6] [7, 8, 9, 10] ### 回答3: 要将一个List分成多个子List,可以使用以下方法: 1. 获取原始List的大小,假设为totalSize。 2. 定义子List的大小,假设为subListSize。 3. 计算需要分成的子List数量,假设为subListCount,可以使用Math.ceil(totalSize / subListSize)来得到向上取整的结果。 4. 创建一个新的ArrayList来存储所有子List,假设为resultList。 5. 根据subListCount,循环subListCount次来创建子List: 1. 计算当前子List的起始索引,假设为start。 2. 计算当前子List的结束索引,假设为end。当达到最后一个子List时,结束索引为totalSize。 3. 使用List的subList方法,将原始List的[start, end)区间的元素作为一个新的子List,并将其添加到resultList中。 6. 返回resultList作为分割好的子List集合。 下面是一个示例代码: ```java import java.util.ArrayList; import java.util.List; public class ListPartition { public static List<List<Integer>> partitionList(List<Integer> originalList, int subListSize) { int totalSize = originalList.size(); int subListCount = (int) Math.ceil((double) totalSize / subListSize); List<List<Integer>> resultList = new ArrayList<>(); for (int i = 0; i < subListCount; i++) { int start = i * subListSize; int end = Math.min(start + subListSize, totalSize); List<Integer> subList = originalList.subList(start, end); resultList.add(subList); } return resultList; } public static void main(String[] args) { List<Integer> originalList = new ArrayList<>(); originalList.add(1); originalList.add(2); originalList.add(3); originalList.add(4); originalList.add(5); List<List<Integer>> partitionedList = partitionList(originalList, 2); for (List<Integer> subList : partitionedList) { System.out.println(subList); } } } ``` 以上示例代码将会把原始List [1, 2, 3, 4, 5] 分成两个子List [1, 2] 和 [3, 4, 5],并打印出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值