gpt4 book ai didi

java - 在java中是否有本地或更快的方法来对列表进行分区?

转载 作者:行者123 更新时间:2023-12-01 19:05:07 24 4
gpt4 key购买 nike

假设我有一个像这样的列表 {1,2,3,4,5,6,7,8}。有没有一种快速的方法来创建两个列表(一个包含前半部分,另一个包含后半部分)?分割的位置始终是列表大小的一半(列表始终是偶数)

目前我的方法是将大小除以 2,然后迭代列表,添加 list1 中低于值的任何内容以及 list2 中高于值的任何内容。我只是想知道是否有更快的方法(我需要做超过十亿次这样的事情,所以即使性能上的微小改进也可以节省我很多时间)。

最佳答案

就内置功能而言,您可以使用List#subList(int, int) :

int size = original.size();
List<Integer> first = original.subList(0, size / 2);
List<Integer> second = original.subList(size / 2, size);

是否要使用subList()取决于您对内容的处理方式。 subList() 将 View 返回到原始列表中(而不是实际复制)。确保您阅读了 javadoc。这是一个片段:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

此外,我无法真正谈论 subList() 的性能以及它如何满足或不满足您的要求。我想,因为它只是创建 View 而不是复制,所以它会相对较快。但同样,情况相当,您需要以任何一种方式对其进行分析才能知道。

关于java - 在java中是否有本地或更快的方法来对列表进行分区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com