Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
}
     
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading