Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using join with an iterator and a String function

Tags:

java

java-8

Suppose I have an Iterator<Class1> object. Class1 provides a method stringFunction() that returns a String.

Is there a way to use String.join in a way that calls stringFunction() on every Class1 returned by the iterator, and concatenates the function results separated by a delimiter?

There's a String.join overload that takes an Iterable<CharSequence>; is it possible to create one from the Iterator<Class1> and the stringFunction, so that join can use it?

like image 824
ajb Avatar asked Aug 30 '26 03:08

ajb


1 Answers

How about using

  • streamOfCharSequence.collect(Collectors.joining(delimiter))

instead of String.join(delimiter, Iterable<CharSequence>.

You can try something like

String result = StreamSupport
        .stream(Spliterators.spliteratorUnknownSize(iterator,
                Spliterator.ORDERED), false)
        .map(e -> e.stringFunction()).collect(Collectors.joining(", "));
like image 133
Pshemo Avatar answered Aug 31 '26 18:08

Pshemo



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!