Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate all the elements of a String ArrayList using method reference in Java 8

I am studying Java 8 and I came across an assignment that tells me to do this. I have it working using lambda but the assignment insists on doing it with method reference.

My code with lambda is

package java8training.unit2;

import java.util.List;

import java8training.artifacts.CentralDataBase;

public class Solution2 {

    public static void main(String[] args) {
        List<String> words = CentralDataBase.words;
        words.stream().map(s -> "  " + s).forEach(System.out::println);
    }
}

At the moment I think it is not possible to replace the lambda

s -> "  " + s

with its method reference, or am I wrong?

like image 879
Atif Karbelkar Avatar asked Jun 07 '26 15:06

Atif Karbelkar


1 Answers

@holi-java in right in his comment. Java has some methods for concatenation like String#concat which you can use here:

" "::concat

Would be the method reference to use.

like image 70
Eugene Avatar answered Jun 09 '26 04:06

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!