简体   繁体   English

Java,如何正确实现列表上的嵌套迭代器?

[英]Java, how to properly implement nested iterators on Lists?

I have two java List<String> objects, and I need to add in a third List<String> result object all the possibile combinations of the first two ones. 我有两个java List<String>对象,并且我需要在第三个List<String>结果对象中添加前两个对象的所有可能组合。 Like: 喜欢:

List<String> list1 = getList1();
List<String> list2 = getList2();

List<String> result = new ArrayList<String>();

for(String value1 : list1) {
    for(String value2 : list2) {
        result.add(value1 + value2);
    }
}

The problem is that this quick and dirty function becomes exponentially slow when the lists grow: 问题在于,当列表增长时,这种快速而肮脏的功能将成倍地变慢:

long combinations = list1.size() * list2.size()

Maybe I'm doing it wrong, is there a better approach to it or any framework that can be used? 也许我做错了,是否有更好的方法或可以使用的任何框架?

您可以通过调用result.size()而不是将大小相乘得到想要的东西吗?

To make it faster, you can provide the initial capacity to the result so that the internal array of ArrayList is not extended: 为了使其更快,您可以为结果提供初始容量,以便不扩展ArrayList的内部数组:

int capacity = list1.size() * list2.size();
List<String> result = new ArrayList<String>(capacity);

The slightly-harder-but-definitely-better way is to extend an unmodifiable AbstractCollection (or AbstractList ) and the associated iterator (that will iterate on the two List iterators as needed). 稍微困难一些但绝对更好的方法是扩展一个不可修改的AbstractCollection (或AbstractList和关联的迭代器(根据需要在两个List迭代器上进行迭代)。 This way you won't need O(N*M) storage for the combined list. 这样,您将不需要O(N * M)存储组合列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM