3

I have a list like below

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("mango");
fruits.add("grapes");
System.out.println(fruits.toString());

I am using lambda expression for printing the list like

fruits.forEach(item->System.out.println(item));

and its working fine my requirement is I need to iterate over the list and concatenate the items to a string

String stringFruits = "";
fruits.forEach(item->stringFruits = stringFruits+item);

this is giving a compile time error saying variable values used in lambda should be effectively final is there any way I can do it in java 8 ?

2
  • 3
    String stringFruits = fruits.stream().collect(Collectors.joining()); Commented May 4, 2017 at 7:55
  • @Eran thanks it worked Commented May 4, 2017 at 7:57

4 Answers 4

7

You need to join via a delimiter. In this case the delimiter is going to be ,; but you can choose any you want.

 String result = fruits.stream().collect(Collectors.joining(","));
 System.out.println(result);
Sign up to request clarification or add additional context in comments.

1 Comment

Big gun for a small problem. In that case, there’s the convenient simple method String.join(…)
4

Java8 introduced a StringJoiner that does what you need (is another alternative to erans comment)

StringJoiner sj = new StringJoiner("-,-");
fruits.forEach(item -> sj.add(item));

here the doc

edit:

for the posterity you can do as well:

String result = fruits.stream().collect(Collectors.joining(","));
System.out.println(result);

or

String stringFruits = String.join(", ", fruits);
System.out.println(stringFruits);

credits and thanks to @Holger

1 Comment

And since this is so practical, there’s String.join(…) already doing that
3

You don’t need to do that by hand at all. If your source is a List, you can just use

String stringFruits = String.join(", ", fruits);
System.out.println(stringFruits);

The first argument to String.join(…) is the delimiter.

Comments

1

Or a pre-Java8 solution:

String combined = "";
for (String s : fruits) {
   combined += s;
}

... and one with delimiter:

String combined = "";
for (String s : fruits) {
   combined = combined + ", " + s;
}

1 Comment

It's usually best to use a StringBuilder when you're looping. Concatentation gets exponentially slower in a loop.

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.