迭代一个arraylist

时间:2012-08-02 09:56:07

标签: java list collections

我有一个对象的ArrayList,如下所示:

对象:

String country;
String languages;
String number;

列表如下:

India, Hindi, 500
India, English, 600
India, Bengali, 800
US, French, 700
Germany, German, 800

上面的列表在我的代码中显示为:

List<MyObject> myList;  // this is the list I want to query

因此myList中有5个MyObject对象,其值如前所述。

对象的语言和国家/地区属性在我的情况下是一个唯一的键。

所以我想根据语言和国家/地区获取相应的数字。

e.g。类似的东西:

getNumber(India, Hindi) should return 500
getNumber(India, Bengali) should return 800

如何以这种方式查询列表?是否可以通过Iterator?

感谢阅读。

6 个答案:

答案 0 :(得分:3)

  

对象的语言和国家/地区属性在我的案例中是一个唯一的键。

听起来你很可能会使用地图然后......

  

如何以这种方式查询列表?是否可以通过Iterator?

绝对 - 它将是O(N),但它很容易做到:

// TODO: Revisit the decision to make a field called "number"
// a string...
String getNumber(String language, String country) {
    for (MyObject candidate : list) {
        if (candidate.getLanguage().equals(language) &&
            candidate.getCountry().equals(country)) {
            return candidate.getNumber();
        }
    }
    // Or throw an exception, depending on what semantics are expected
    return null;
}

答案 1 :(得分:2)

使用列表的唯一方法是遍历所有对象并找到具有给定国家/地区和语言的对象。

如果您制作了一个包含国家/地区和语言的MyKey课程,并根据这两个字段覆盖equals()hashCode(),那么效率会更高。然后,您可以使用HashMap<MyKey, MyObject>,并通过调用以下方式获取对象:

MyObject o = map.get(new MyKey(country, language));

答案 2 :(得分:1)

public int getCodeByCountryAndLanguage(String country, String language){
    for(MyObject candidate : mylist){
        if(candidate.country.equals(country) 
           && candidate.language.equals(language)){
            return candidate.number; 
        }
    }
    return -1;
}

答案 3 :(得分:1)

这样的事情:

int getNumber(country, language) {
    int number = -1;
    for(MyObject obj : myList) {
        if(country.equals(obj.country) && language.equals(obj.country)) {
            value = obj.number;
            break;
        }
    }
    return number;
}

答案 4 :(得分:0)

是的,可以使用迭代器来完成此操作。它大致如下:

for(MyObject m : myList) {
    if (   "India".equals(m.getCountry())
        && "Hindi".equals(m.getLanguages())) {

        return m.getNumber();
    }
}

但是,您也可以考虑将countrylanguage字段移至单独的类别,例如MyListKey,该字段具有正确的equals()hashCode()方法,然后使用Map<MyListKey, String>。那么你的代码就是:

return myMap.get(new MyListKey("India", "Hindi"));

答案 5 :(得分:0)

如果对象的顺序不重要,则应更改为使用Map。

您可以使用迭代器并比较输入值以查找结果

如果您想要排序,请考虑使用集合。 MyObject应该扩展Comparable