Skip to content
Advertisement

reusing stream inside a stream java

Hi I just wanted to know what is wrong with my code and how can I improve it as it throws an error “stream has already been operated upon or closed” thank you here is my code:

Stream<String> stream = Files.lines(path)

stream.filter(item -> !item.contains("String")).forEach(item -> {
            Pattern pattern = Pattern.compile(REGEX);
            Matcher matcher = pattern.matcher(item);
            if (!stream.filter(items -> items.length() > 12).collect(Collectors.toList()).isEmpty() == true) {
                log.error("Item must not exceed 12 numbers {}", item);
                streamMessage.set("Items must not exceed 12 numbers");
            }
            else if(matcher.matches() == true){
                log.error("Invalid String format {}", item);
                streamMessage.set("Invalid String format");
            }
        });

I wanted to loop inside the file and check per line if the characters there exceeded 12 characters or not

Advertisement

Answer

You cannot reuse the Stream. You can create two Streams using Files.lines(path), but given your code, I don’t think it’s necessary.

You can find all the elements that are too long using a single Stream:

List<String> tooLong = 
    stream.filter(item -> !item.contains("String"))
          .filter(items -> items.length() > 12)
          .collect(Collectors.toList());

if (tooLong.size () > 0) {
    log.error("Items must not exceed 12 numbers {}", tooLong.toString ());
    streamMessage.set("Items must not exceed 12 numbers");
}
     

EDIT:

After your question edit, it appears you want to do two checks for each element of the Stream. You can still do it with a single Stream:

stream.filter(item -> !item.contains("String"))
      .forEach(item -> {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(item);
        if (item.length() > 12) {
            log.error("Item must not exceed 12 numbers {}", item);
            streamMessage.set("Items must not exceed 12 numbers");
        } else if(matcher.matches()) {
            log.error("Invalid String format {}", item);
            streamMessage.set("Invalid String format");
        }
    });
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement