ehsan ehsan - 4 months ago 16
Java Question

How can I make copies of a Stream so when it is used I use the duplicate in Java 8?

This is how my code looks :

public static String firstContainsChars(Stream<String> items,String charset) {
char[] inChars = charset.toCharArray();
for (char ch:inChars) {
items.filter(s->s.contains(String.valueOf(ch)));
}
return items.findFirst().orElse("No Match Found");
}


In fact, I am getting a collection of chars as a
String
and
filter
the stream but the problem is I can't use the stream several times in the
foreach
loop and compiler says :

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed


Any ideas on how to duplicate the Stream without the need to collect it as a
Collection
as it will be total waste. (streaming and collecting after the chnage)?

Answer

As I said in the comment section you have to assign items to the new pipeline in the loop.

public static String firstContainsChars(Stream<String> items, String charset) {
  char[] inChars = charset.toCharArray();
  for (char ch : inChars) {
    items = items.filter(s -> s.contains(String.valueOf(ch)));
  }
  return items.findFirst().orElse("No Match Found");
}

But a much cleaner approach would be to Stream your charset too, like:

public static String firstContainsChars(Stream<String> items, String charset) {
  return items.filter(s -> charset.codePoints().allMatch(cp -> s.indexOf(cp) != -1))
              .findFirst().orElse("No Match Found");
}