想要在ArrayList中获取带有id列表的元素

时间:2013-06-14 06:35:06

标签: java arrays arraylist

我有ArrayList<UIToto>,每个UIToto包含

(String id, String name, String info)

例如

(4546-fdsf4545sfd-dfs545, titi, female)
(dqs4d65q4-45d4s54545sfd-dfss54545, tutu, male)

我有一个像

这样的ID列表
String ids = "dqs4d65q4-45d4s54545sfd-dfss54545, 4545-dsqd45-dqs,4d5s44-ss4-dqsd";

对于每个id,我检索id,我想在我的ArrayList中获取UIToto:

ArrayList<UIToto> totoList = retrieveTotoList();
String[] ids = "dqs4d65q4-45d4s54545sfd-dfss54545, 4545-dsqd45-dqs,4d5s44-ss4-dqsd";
for(int i=0; i <= ids.length; i++) {
    System.out.println(("id = " + ids[i]);
    //don't work because it's not the index but the id ...
UIToto response = totoList.get(Integer.parseInt(ids[1]));
System.out.println("response = " + response);
 }

有可能吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

尝试

ArrayList<UIToto> totoList = retrieveTotoList;
ArrayList<UIToto> resultList= new ArrayList<UIToto>();

String[] ids = {"dqs4d65q4-45d4s54545sfd-dfss54545", 
                "4545-dsqd45-dqs,4d5s44-ss4-dqsd"}; 

for(int i = 0; i < ids.length; i++) {
    for(UIToto uIToto : totoList) {
        if(uIToto.getId().equals(ids[i])) {
            resultList.add(uIToto);     
        }
    }
}

答案 1 :(得分:0)

根据您的用例,当您需要根据对象的某个值在集合中查找对象时,使用string-id作为键的Map可能比arrayList更优雅。

public static void main(String argv) {
    Map<String, UIToto> totoMap = getTotoMap();
    String[] ids = {"dqs4d65q4-45d4s54545sfd-dfss54545", "4545-dsqd45-dqs,4d5s44-ss4-dqsd"};
    for(int i=0; i <= ids.length; i++) {
        System.out.println(("id = " + ids[i]));

        UIToto response = totoMap.get(ids[i]);
        System.out.println("response = " + response);
    }
}

//Example how to Construct the map with the String as ID. 
//Ideally the map would be constructed without first creating the list
public Map<String,UIToto> getTotoMap() {
    Map<String, UIToto> totoMap = new HashMap<String, UIToto>();
    List<UIToto> totoList = retrieveTotoList();
    for (UIToto uiToto :totoList) {
        totoMap.put(uiToto.getId(), uiToto);
    }
}