以循环方式加入Java中的列表

以循环方式加入Java中的列表

本文介绍了以循环方式加入Java中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中循环多个ArrayList.有没有简单的方法可以实现它?

I need to round robin multiple ArrayLists in java. Is there any simple way to achieve it?

lists = [1,2,3], [4,5], [6,7,8]

结果应为:

[1,4,6,2,5,7,3,8]

推荐答案

tl; dr

循环显示列表,以最大大小循环播放.从每个列表中拉出第n个元素.当我们要求第n个元素超出其大小时,较短的列表将引发异常.只需忽略该异常即可.

tl;dr

Loop the list of lists, looping for the maximum size. Pull the nth element from each list. The shorter lists will throw an exception when we ask for the nth element beyond their size; just ignore that exception.

List < List < Integer > > listOfLists =
        List.of(
                List.of( 1 , 2 , 3 ) ,
                List.of( 4 , 5 ) ,
                List.of( 6 , 7 , 8 )
        );
OptionalInt longestLength = listOfLists.stream().mapToInt( List :: size ).max();
int limit = longestLength.orElse( 0 );

int initialCapacity = listOfLists.stream().mapToInt( List :: size ).sum();
List < Integer > results = new ArrayList <>( initialCapacity );

for ( int i = 0 ; i < limit ; i++ )
{
    for ( List < Integer > listOfIntegers : listOfLists )
    {
        try
        {
            Integer integer = listOfIntegers.get( i );
            results.add( integer );
        }
        catch ( IndexOutOfBoundsException e )
        {
            // Do nothing. Swallow exception. We expect to fall out of bounds on shorter lists.
        }
    }
}
return List.copyOf( results ) ;

可以通过检查是否经过短数组的末尾而不是抛出异常来改进此方法.但是在这种情况下,我认为没有什么意义.

This approach might be improved by checking to see if we went past the end of the shorter arrays, rather than throwing an exception. But in this case I do not see much point in that.

定义我们的列表.

List < List < Integer > > listOfLists =
        List.of(
                List.of( 1 , 2 , 3 ) ,
                List.of( 4 , 5 ) ,
                List.of( 6 , 7 , 8 )
        );

确定列表的最长长度.

OptionalInt longestLength = listOfLists.stream().mapToInt( List :: size ).max();
int limit = longestLength.orElse( 0 );

限制= 3

建立一个列表以捕获我们的结果.

Build a list to capture our results.

int initialCapacity = listOfLists.stream().mapToInt( List :: size ).sum();
List < Integer > results = new ArrayList <>( initialCapacity );

遍历每个列表,而忽略在较短列表上抛出的任何 IndexOutOfBoundsException .

Loop through each list, ignoring any IndexOutOfBoundsException thrown on the shorter lists.

for ( int i = 0 ; i < limit ; i++ )
{
    for ( List < Integer > listOfIntegers : listOfLists )
    {
        try
        {
            Integer integer = listOfIntegers.get( i );
            results.add( integer );
        }
        catch ( IndexOutOfBoundsException e )
        {
            // Do nothing. Swallow exception. We expect to fall out of bounds on shorter lists.
        }
    }
}

请参见此在IdeOne.com上实时运行的代码.

返回无法修改的列表.

return List.copyOf( results ) ;

这篇关于以循环方式加入Java中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 21:47