如何使用Java ArrayList提高性能 [英] How to increase the performance with Java ArrayList

查看:55
本文介绍了如何使用Java ArrayList提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有以下代码的巨大ArrayList

I'm using a huge ArrayList with the code bellow

public final List<MyClass> list = new ArrayList<>();

public void update(MyClass myClass) {
int i;
for (i=0; i < list.size(); i++) {
        if (myClass.foo(list.get(i))) {
            list.set(i, myClass);
            break;
        }    
    }    
    if (i == list.size()) {    
        list.add(myClass);    
    }    
}

此列表非常大。在这种情况下,我还能采取其他措施来提高性能吗?也许使用某些Java 8功能,替换了ArrayList或类似的东西。

The list is extremely large. There is something else that I can do to increase the performance with this scenario? Maybe using some Java 8 feature, replacing ArrayList or something like that.

与此列表相关的另一个运行时间太长的代码是下面的代码:

Another code that is taking too long to run related this List is the code bellow:

public List<MyClass> something(Integer amount) {
list.sort((m1, m2) -> Double.compare(m2.getBar(), m1.getBar()));
return list.stream()
        .limit(amount)
        .collect(Collectors.toList());
}

欢迎任何帮助,谢谢大家

Any help is welcome, thank you all

推荐答案

似乎选择 ArrayList 不好。

It seems like the choice of the ArrayList is not good.

在第一种情况,您尝试通过列表中对象的属性查找对象。要在列表中找到对象,您必须检入列表中的每个元素。列表越大,则列表越长。 (使用ArrayList的情况下,O(N)的复杂度最差)

In the first case, you attempt to find an object by his properties in the list. To find an object in the list, you have to check in each elements of your list. Bigger is the list, the longer it will be. (You have a worst case complexity of O(N) with ArrayList)

如果使用 HashMap 而不是列表,您可以将属性用作地图的键。这样,您可以选择需要直接更新的对象,而无需检查列表中的每个元素。执行时间将不再取决于条目数。 (使用HashMap时,您的O(1)复杂度最差)

If you use an HashMap instead of a List, you can use your property as key of your map. Like this, you can select the object you need to update directly without check each element of your list. The execution time will be no more dependent of the number of entries. (You have a worst case complexity of O(1) with HashMap)

如果使用 HashMap 而不是 ArrayList ,您的更新代码将如下所示:

If you use HashMap instead of ArrayList, your update code gonna look like this:

public void update(MyClass myClass) {
    map.put(myClass.getKey(), myClass);
}

(其中 getKey()是您尝试在foo方法中等于的属性。)

(where getKey() is the properties you try to equals in your foo method).

但这仅用于第一种情况。有了这些信息,我们似乎是最好的解决方案。

But this is only for the first case. With the informations we have it seems the best solution.

这篇关于如何使用Java ArrayList提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆