0

I have a list of data in the iterator.I want to store it in a string. How can I do it? Here is my code.

List ln = readData(iStepNumber, status, query);

Iterator itr = ln.iterator();

System.out.println("listttt"+ln);

while(itr.hasNext()) {
    System.out.println("itr value1 :"+itr.next());
    //what to do to store itr.next() in a string
    //for example String a=itr.next()?
}

This is what I get in the console

listttt[2017-06-30 23:59:59]
itr value1 :2017-06-30 23:59:59
2
  • Use a StringBuilder or StringBuffer to build your string together, if you need all the items in your list in the same string Commented Jun 12, 2017 at 13:23
  • You should specify which kind of string you are expecting. String.join(",", ln) might be what you're looking for, but then I don't see what's wrong with your current output. Commented Jun 12, 2017 at 13:23

4 Answers 4

2

Instead of just printing itr.next(), save it to a string variable like this:

String yourString = itr.next();

If you have more than one item in the list, you can either do yourString += itr.next(), or use a StringBuilder and StringBuilder.append(), which is much more efficient.

Sign up to request clarification or add additional context in comments.

Comments

1

You should use stringbuffer

List ln = readData(iStepNumber, status, query);
Iterator itr = ln.iterator();
System.out.println("listttt"+ln);

StringBuffer sBuffer = new StringBuffer();

while(itr.hasNext()){
  sBuffer.append(itr.next());
  System.out.println("itr value1 :"+itr.next());
}

Comments

0

Just implement toString() method in your object and output the list using System.out.println(list). This will display all the data without any need of iteration manually in your code.

Comments

0

You can use Java 8 stream API.
Take your list of respective object type

List<Object> ln = readData(iStepNumber, status, query);
Iterator itr = ln.iterator();
System.out.println("listttt"+ln);

// Now call the stream() method on list 

 String data=ln.stream()  
               .map(Object::toString)  
               .collect(Collectors.joining(","));

// Here use whatever you want as string in joining method string and print 
// or do what ever you want with string data.

System.out.println(data);  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.