package com.tzld.piaoquan.recommend.server.util;

import com.google.common.collect.Lists;

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

/**
 * 合并多个List
 *
 * @author sunxy
 */
public class ListMerger {

    public static <T> List<T> mergeLists(List<T> list1, List<T> list2, List<T> list3) {
        List<T> result = new ArrayList<>();
        int maxSize = Math.max(list1.size(), Math.max(list2.size(), list3.size()));

        for (int i = 0; i < maxSize; i++) {
            if (i < list1.size()) {
                result.add(list1.get(i));
            }
            if (i < list2.size()) {
                result.add(list2.get(i));
            }
            if (i < list3.size()) {
                result.add(list3.get(i));
            }
        }

        return result;
    }

    public static <T> List<T> mergeLists(List<List<T>> lists) {
        List<T> result = new ArrayList<>();
        int maxSize = 0;
        for (List<T> list : lists) {
            maxSize = Math.max(maxSize, list.size());
        }

        for (int i = 0; i < maxSize; i++) {
            for (List<T> list : lists) {
                if (i < list.size()) {
                    result.add(list.get(i));
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        // 示例
        List<Integer> list1 = Lists.newArrayList(1, 4, 7);
        List<Integer> list2 = Lists.newArrayList(2, 5, 8, 10, 11);
        List<Integer> list3 = Lists.newArrayList(3, 6, 9);

        List<Integer> mergedList = mergeLists(list1, list2, list3);
        System.out.println(mergedList);
    }
}
