如何使for循环代码块运行得更快?

问题描述

这是twitter4j依赖项。我正在获取用户关注者的数据。

下面的代码需要近 15秒才能完成提取 45个用户数据的过程。如何使此代码运行更快?还是我应该大致添加项目逻辑?

多线程?并发?

ArrayList<String> list = new ArrayList<String>();
int i = 0;
try {

    IDs ids = twitter.getFollowersIDs(-1);// ids

    do {
        for (long id : ids.getIDs()) {
            String location = twitter.showUser(id).getLocation();
            if(location.length() != 0) {
                list.add(location);
                System.out.println(location);
            }
            i++;
        }
    } while (ids.hasNext());

} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(i);
return list;

解决方法

您可以创建多个线程来同时处理数据。

此外,如果twitter库支持流,则可以使用parallelStream()自动做到这一点。

类似的东西:

IDs ids = twitter.getFollowersIDs(-1); // ids

List<String> locations = ids.getIDs().parallelStream()
    .map(twitter::showUser)
    .map(TwitterUserClass::getLocation)
    .filter(location -> location.length() != 0)
    .collect(Collection.asList());

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...