java—是否可以使这个嵌套for循环小于o(n^2)?

piok6c0g  于 2021-06-07  发布在  Kafka
关注(0)|答案(1)|浏览(315)

我正在使用apachespark2.1和java8开发kafka流媒体服务。我用嵌套的 for 循环以填充 ArrayList 主题/分区对。
有没有可能减少这一点 for 使用另一种方法从o(n^2)循环?
代码如下:

private static List<TopicAndPartition> createTAndPList(List<String> topics, List<String> partitions)
        throws ConsumerException {
    if (topics.size() != partitions.size()) {
        throw new ConsumerException("Cannot create list with unequal number of topics and parititons,");
    }

    List<TopicAndPartition> topicsAndPartitions = new ArrayList<>();
    for (int t = 0; t < topics.size(); t++) {
        for (int p = 0; p < Integer.parseInt(partitions.get(t)); p++) {
            topicsAndPartitions.add(new TopicAndPartition(topics.get(t), p));
        }
    }

    return topicsAndPartitions;
}

仅供参考:我无法使用以上Kafka8由于权力超出我的控制(管理)

xkftehaa

xkftehaa1#

对于给定的代码,似乎不可能减少顺序。
但是,您可以进行两个小的优化。
移动主题。从内部for循环中取出(t),
不要为每个循环重新计算内部for循环终止条件。

for (int t = 0; t < topics.size(); t++) {
    String topic = topics.get(t);
    int count = Integer.parseInt(partitions.get(t));    
    for (int p = 0; p < count; p++) {
        topicsAndPartitions.add(new TopicAndPartition(topic, p));

您正在调用topics.get和integer.parseint(partitions.get(t))t*p次,而不是仅仅调用t次。topics.get()的更改可能不会有多大作用,但是像这样将某些内容移出内部循环是一种非常常见的优化。
最后,你真的需要把它们都列在一张单子里吗?或者你能在你真正需要它们的地方动态地生成它们吗?

相关问题