0

I have a string where i need to place the values from the list,But when i for loop the list i will get one value at a 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 is "+value.get(i) +"  age is "+value.get(i)+" country is"+value.get(i);
        System.out.println(value.get(i));
        }
    o/p should be like this:    String ="My name is +"+RAM +"age is "+26+"Country is"+INDIA;
    }
}
user7352962
  • 25
  • 2
  • 8

3 Answers3

1

You don't need a for loop, simply access the elements using index of the List as shown below:

System.out.println("My name is "+value.get(0) +
  "  age is "+value.get(1)+" country is"+value.get(2));

Also, I suggest you use StringBuilder for appending strings which is a best practice, as shown below:

StringBuilder output = new StringBuilder();
        output.append("My name is ").append(value.get(0)).append("  age is ").
            append(value.get(1)).append(" country is ").append(value.get(2));
System.out.println(output.toString());
Vasu
  • 21,832
  • 11
  • 51
  • 67
0

You do not need any loop! Also you do not need any array list I am sorry but I could fully understand what exactly you need but I this code will help you:

    List<String> value = new ArrayList<String>();
    value.add("RAM");
    value.add("26");
    value.add("INDIA");

    String template = "My name is " + value.get(0) + "  age is " + value.get(1) + " country is" + value.get(2);
    System.out.println(template);

    // o/p should be like this: String ="My name is +"+RAM +"age is
    // "+26+"Country is"+INDIA;
0

What's happening is that in each iteration you're taking the i-th element of the list and you're placing it in all the positions of your String template.

As @javaguy says, there's no need to use a for loop if you only have those three items in your list, and another solution is to use String.format:

String template = "My name is %s age is %s country is %s";
String output = String.format(template, value.get(0), value.get(1), value.get(2));

It's probably a bit slower (interesting discussion here) but performances don't seem to be relevant in your case, so the choiche between the two options would be mostly based on personal taste.

Community
  • 1
  • 1
Stefano Zanini
  • 5,876
  • 2
  • 13
  • 33