淘先锋技术网

首页 1 2 3 4 5 6 7

可参考这篇:https://www.codeleading.com/article/73564703440/

package com.garfield.collectors.util;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.collect.Lists;

/**
 * @author zhaojian
 * @date 2021/7/20
 */
public class ArraysUtil {
    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

    /**
     * guava分割其他collections plain
     */
    public static <T> List<List<T>> averageListByGuava(List<T> list) {
        return Lists.partition(list, 3);
    }

    /**
     * java8 使用groupingBy
     * @param list
     * @return
     */
    public static List<List<Integer>> averageListByStream(List<Integer> list) {

        Map<Integer, List<Integer>> groups =
                list.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
        return new ArrayList(groups.values());
    }


    public static void main(String[] args) {
        List<Integer> list = Stream.of(1, 2, 3, 4, 5, 6, 7, 8).collect(Collectors.toList());
        List<List<Integer>> averageList = averageAssign(list, 3);
        averageList.get(0).forEach(System.out::print);
        System.out.println("averageAssign****");
        averageList.get(1).forEach(System.out::print);
        System.out.println("averageAssign****");
        averageList.get(2).forEach(System.out::print);
        System.out.println();

        List<List<Integer>> result1 = averageListByGuava(list);
        result1.get(0).forEach(System.out::print);
        System.out.println("使用guava");
        result1.get(1).forEach(System.out::print);
        System.out.println("使用guava");
        result1.get(2).forEach(System.out::print);
        System.out.println();

        List<List<Integer>> result2 = averageListByStream(list);
        result2.get(0).forEach(System.out::print);
        System.out.println("averageListByStream");
        result2.get(1).forEach(System.out::print);
        System.out.println("averageListByStream");
        result2.get(2).forEach(System.out::print);

    }
}