简体   繁体   中英

Java Streams: Is there a cleaner way of doing this?

I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.

import java.util.Arrays;
import java.util.List;

public class QuestionNine {
    public static void main(String[] args) {
        new QuestionNine().launch();
    }
    public void launch(){
        List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What", 
                                           "Dog", "boat", "Egg", "Queen", "Soq", "Eet");
        String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
        result = result.substring(0, result.length() -1); //removes last comma
        System.out.println(result);
    }
}

Instead of using the String.substring() method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?

The usual idiom is to use the joining Collector with Streams.

String res = words.stream().collect(Collectors.joining(","));

Although you can use String.join in your case since you are directly dealing with an Iterable .

String res = String.join(",", words);

The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:

.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);

but I don't recommend this.

Yes, you can use Collectors.joining() here:

String joined = words.stream().collect(Collectors.joining(", "));

Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable) method.

String joined = String.join(", ", words);

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