迭代后检索值

时间:2012-08-05 16:50:07

标签: java hashmap

在遍历“hashmap list”之后,我想将值写入字符串中,作为“value 1”和“value 2”。我怎么也想不出来?有人可以帮帮我!

for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);

我的数据中有2个值。上面的代码给了我

缺点:名称

缺点:ID

现在,我希望'Name'为值1,'ID'为值2,以便我可以在以下字符串中替换和写入它们

"xxxxxxxxxx"+key+"xxxx"+value 1+"xxxxxxxxx"+value 2+"xxxxxxxxxx";

2 个答案:

答案 0 :(得分:1)

尝试:

String value1="";
String value2="";
int counter=0;

for (Object listItem : (List)value) {
    System.out.println(key + ":" + listItem);

    if(counter==0) {//first pass assign value to value1
       value1=listItem; 
       counter++;//increment for next pass
    }else if(counter==1) {//second pass assign value to value2
        value2=listItem;
        counter++;//so we dont keep re-assigning listItem for further iterations
    }

}

System.out.println(value1);//should display 'Name'
System.out.println(value2);//should display 'ID'

答案 1 :(得分:0)

使用StringBuilder类(假设key在循环之外定义)

StringBuilder sb = new StringBuilder("xxxxxx" + key + "xxxx");
for (Object listItem : (List)value) {
    System.out.println(key + ":" + listItem);
    sb.append(listItem+"xxxxxxxxx");
}