Problem with lambda java8 and foreach expression
I have a list below
List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("mango");
fruits.add("grapes");
System.out.println(fruits.toString());
I am using a lambda expression to print a 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 elements into a string
String stringFruits = "";
fruits.forEach(item->stringFruits = stringFruits+item);
this gives a compile-time error that the values of the variables used in the lambda must be definitively final , is there a way to do this in java 8?
+3
source to share
4 answers
You don't need to do it manually. If your source is List
, you can simply use
String stringFruits = String.join(", ", fruits);
System.out.println(stringFruits);
The first argument String.join(…)
is a separator.
+3
source to share
Java8 introduces StringJoiner , which does what you want (this is another alternative to the default comment)
StringJoiner sj = new StringJoiner("-,-");
fruits.forEach(item -> sj.add(item));
here doc
edit:
for posterity, you can also do:
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
+4
source to share