简体   繁体   中英

Print each element of ArrayList and use it in String java

I would like to take each element of ArrayList and use it to create a String that:

  1. contains as many words as elements of the ArrayList and,
  2. the int value from the ArrayList is printed for each of the words.

To make it clearer I want to print a String that will look like this:

System.out.println(result);
element(0), element(1), element(2), element(3)

Unfortunately, I'm only getting the value of the last Integer from the ArrayList, but the number of 'element' words is correct, so my actual result String looks like that:

System.out.println(result);
element(3), element(3), element(3), element(3)

The ArrayList has only 4 elements:

[0, 1, 2, 3]

To produce this incorrect String I'm using the following code:

List<Integer> intList = new ArrayList<Integer>();
int intValue;
String result;

int n = intList.size();
for (int i=0; i < n; i++) {
    intValue = intList.get(i);
    result = String.join(", ", java.util.Collections.nCopies(n,  "element("+intValue+")"));
}

So how can I make a correct String with all values of the ArrayList?

Here:

for ... {
  result = String.join(...)
}

Within your loop you re-assign that joined string to your result during each iteration. In other words: in loop (n) you throw away what was created in loop (n-1).

Try using += instead. Or just go with:

StringBuilder builder = new StringBuilder;
for ... {
  builder.append(...
}
String finalResult = builder.toString();

instead.

As using a builder:

  • makes your intent more clear (you intend to build one string in the end)
  • gives some slight performance improvements (which do not really matter given the "small scale" here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM