如何将数组拆分为基于JAVA流的元素

时间:2018-03-20 04:45:44

标签: java arrays

我需要使用java streams API将数组拆分为以下方式

int [] arr = {1,3,5,8,9}

{1,3,5}, {3,5,8}, {5,8,9}

1 个答案:

答案 0 :(得分:0)

要做同样的事情,我们也可以使用如下所示的分组: -

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class SplitList
{
    // Generic function to split a list in Java 8
    public static<T> List[] split(List<T> list)
    {
        int midIndex = (list.size() - 1) / 2;

        List<List<T>> lists = new ArrayList<>(list.stream()
                                .collect(Collectors.groupingBy(s -> list.indexOf(s) > midIndex))
                                .values());

        // return an array containing both lists
        return new List[] {lists.get(0), lists.get(1)};
    }

    // Program to split a list in Java
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("A", "B", "C", "D", "E");

        // split list into two
        List[] lists = split(list);

        System.out.println(lists[0]);
        System.out.println(lists[1]);
    }
}

进一步查询检查链接: - http://www.techiedelight.com/split-list-two-sublists-java/