1

我有一个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);
 }

是否可以?

谢谢!

4

2 回答 2

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);     
        }
    }
}
于 2013-06-14T06:41:07.693 回答
0

根据您的用例,当您需要根据对象的一个​​值在集合中查找对象时,以字符串 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);
    }
}
于 2013-06-14T07:17:45.427 回答