按指定大小,分隔集合,将集合按规定个数分为n个部分


Java技术学习 https://www.itkc8.com

package com.ybf.common;/**
 * Created by HUXU on 2017/12/9.
 */

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

/**
 * 分割list
 *
 * @author huxu
 * @create 2017-12-09 17:20
 **/

public class ListCommon {

    /**
     * 按指定大小,分隔集合,将集合按规定个数分为n个部分
     *
     * @param list
     * @param len
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }
        List<List<T>> result = new ArrayList<List<T>>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }


}

 

 

 

 

 

 

1、自己编写相关代码:

2、使用guava:

 

[html] view plain copy

  1. import java.util.ArrayList;    
  2. import java.util.List;    
  3. import com.google.common.collect.Lists;    
  4.     
  5.     
  6. public class Test4 {    
  7.     
  8.     public static void main(String[] args) {    
  9.         List<Long> list = new ArrayList<>();    
  10.         list.add(1L);    
  11.         list.add(2L);    
  12.         list.add(3L);    
  13.         list.add(4L);    
  14.         list.add(5L);    
  15.         list.add(6L);    
  16.         list.add(7L);    
  17.         list.add(8L);    
  18.         list.add(9L);    
  19.             
  20.         //test1(list);    
  21.         test2(list);    
  22.     }    
  23.         
  24.     private static void test1(List<Long> list) {    
  25.         int size = 2;    
  26.         List<List<Long>> listArr = new ArrayList<>();      
  27.             
  28.         int arrSize = list.size()%size==0?list.size()/size:list.size()/size+1;      
  29.         for(int i=0;i<arrSize;i++) {      
  30.             List<Long>  sub = new ArrayList<>();      
  31.             for(int j=i*size;j<=size*(i+1)-1;j++) {      
  32.                 if(j<=list.size()-1) {      
  33.                     sub.add(list.get(j));      
  34.                 }      
  35.             }      
  36.             listArr.add(sub);      
  37.         }      
  38.         System.out.println(listArr.toString());    
  39.     }    
  40.         
  41.         
  42.     private static void test2(List<Long> list) {    
  43.         int size = 16;    
  44.         List<List<Long>> subSets = Lists.partition(list, size);      
  45.         System.out.println(subSets.toString());    
  46.     }    
  47. }    

 

 

补充:guava分割其他collectionsiew plain

[html] view plain copy

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

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

 

[html] view plain copy

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


3、使用apache commons collection:

 

 

 

 

[html] view plain copy

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

 

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

 

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

 

4、Java8方法

 

 

1)通过grouping by:

 

[html] view plain copy

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


按年龄分组:

 

[html] view plain copy

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


2)通过partition by:

 

[html] view plain copy

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

 

按照成年未成年人分组:

 

 

[html] view plain copy

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

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

Java技术学习 https://www.itkc8.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值