java - Get Values from List and insert into String -
i have string need place values list,but when loop list 1 value @ iteration.
public class test2 { public static void main(string[] args) throws parseexception, jsonexception { list<string> value=new arraylist<string>(); value.add("ram"); value.add("26"); value.add("india"); for(int i=0;i<value.size();i++){ string template="my name "+value.get(i) +" age "+value.get(i)+" country is"+value.get(i); system.out.println(value.get(i)); } o/p should this: string ="my name +"+ram +"age "+26+"country is"+india; } }
what's happening in each iteration you're taking i-th element of list , you're placing in positions of string template.
as @javaguy says, there's no need use for
loop if have 3 items in list, , solution use string.format
:
string template = "my name %s age %s country %s"; string output = string.format(template, value.get(0), value.get(1), value.get(2));
it's bit slower (interesting discussion here) performances don't seem relevant in case, choiche between 2 options based on personal taste.
Comments
Post a Comment