当前位置: 动力学知识库 > 问答 > 编程问答 >

partitioning - Is there a native or faster way to partition a list in java?

问题描述:

say I have a list like this {1,2,3,4,5,6,7,8}. Is there a fast way to create two lists(one with the first half and the other with the second half)? The location of the split is always half the size of the list(lists are always even numbers)

Currently my approach is to divide the size by 2 and then iterate the list adding anything below the value in list1 and anything above in list2. I was just wondering if there was a quicker way(I need to do over a billion of these, so even a slight improvement in performance can save me alot of time).

网友答案:

As far as built-in functionality, you could use List#subList(int, int):

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

Whether or not you want to use subList() depends on what you're doing with the contents. subList() returns views into the original list (instead of actually copying). Make sure you read the javadoc. Here's a snippet:

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.

Also, I can't really speak to the performance of subList() and how it may or may not meet your requirements. I'd imagine since it's just creating views and not copying that it'd be relatively fast. But again, pretty situational, and you'd need to profile it either way to know.

网友答案:

Ok, you have to do over a billion of theese - fun.

You should profile different methods.

My bet would be to use arrays and System.arraycopy

If your code isn't the code producing the lists, it depends on which implementation of List you are being provided.

You'd be given a better answer if you we're providing more details about the requirements. Is a copy necessary or is a view (as provided by subList() enought). Which implementation of List are you using/being provided etc. The speed is also going to be affected by jvm (version and platform).

分享给朋友:
您可能感兴趣的文章:
随机阅读: