Reputation: 33
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
Upvotes: 0
Views: 142
Reputation: 113
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);
Upvotes: 0
Reputation: 3945
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.
Upvotes: 0
Reputation: 3264
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());
}
Upvotes: 1
Reputation: 352
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.
Upvotes: 2