user1549861
user1549861

Reputation: 11

retrieve values after iteration

After iterating over a "hashmap list", I want to write the values into a string as 'value 1' and 'value 2'. I cannot figure how?Can someone help me!

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

I have 2 values in my data. The above code gives me

Con:Name

Con:ID

Now, I want 'Name' to be value 1 and 'ID' to be value 2 so that I can replace and write them in the following string

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

Upvotes: 1

Views: 83

Answers (2)

David Kroukamp
David Kroukamp

Reputation: 36423

Try:

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'

Upvotes: 1

SomeKittens
SomeKittens

Reputation: 39522

Using the StringBuilder class (assuming key is defined outside of the loop)

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

Upvotes: 0

Related Questions