6

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?

3 Answers 3

11

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(", "));
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that's better. Thanks.
You are welcome. If you are able to get stream then skip whole calling iterator StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) and just use stream().map(e -> e.stringFunction()).collect(Collectors.joining(", ")).
4

Using Guava, you should be able to do something like this:

Iterator<Class1> iter = ...
String result = Joiner.on("//").join(Iterators.transform(iter, x -> x.stringFunction()));

Comments

1

The following works, but seems a little clunky.

Iterator<Class1> iterator = ...;

Iterator<CharSequence> funcIterator = 
  StreamSupport.stream(
    Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
  .map(x -> (CharSequence)x.stringFunction())
  .iterator();

String result = String.join("//", () -> funcIterator);

It doesn't work to create an Iterator<String> because join doesn't accept it; thus it's necessary to declare the type as Iterator<CharSequence>, and also to cast the String to a CharSequence in the lambda. The syntax () -> idIterator works for creating an Iterable whose iterator is the given iterator.

Is there a simpler way?

2 Comments

this should be part of question.. isn't it ?
Depends on how you look at it, I guess ... the original question is the one I was trying to find an answer for, and I found one, and I'm hoping the answer will help someone else. But I'm still hoping there's a simpler answer.

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.