simplify java stream to return an error message
Hi I am new to stream in java I am trying to find which item inside a file has more than 12 of length also if that item has letters mixed in it and wanted to know if this can be simplified using stream in java without using the forEach method in java stream:
Stream<String> stream = Files.lines(path)
stream.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("Item must not exceed 12 numbers");
}
else if (matcher.matches()) {
log.error("Invalid Item format {}", item);
streamMessage.set("Invalid Item format");
}
});
I also need it to return the log.error messages and the stream message thank you
EDIT:
I have tried Glare storm's answer but the message being returned by this:
Stream<String> lengthStream =
stream.filter(item -> item.length() > 12);
Pattern pattern = Pattern.compile(REGEX);
Stream<String> letterStream =
lengthStream.filter(pattern.asPredicate());
if(lengthStream != null){
log.error("Item must not exceed 12 numbers");
message = "Item must not exceed 12 numbers";
}
if(letterStream != null){
log.error("Invalid Item format");
message = "Invalid Item format";
}
it always return Invalid Item format even tho there are no letters inside the file and only has exceeded 12 in length
Use the filter method:
Stream<String> stream = Files.lines(path);
Stream<String> filteredStream= stream .filter(str -> str.length() > 12);
Stream<String> matching = filteredStream.filter(str -> Pattern.matches(regex, str));
or:
Stream<String> matching = filteredStream.filter(str -> {
if(str.length() > 12 && Pattern.matches(regex, str))
return true;
return false;
});
To set error messages you prolly will have to throw an error that will return what ever message you want:
try{
Stream<String> matching = filteredStream.filter(str -> {
if(str.length() > 11 )
throw new Exception("Item must not exceed 12 numbers");
if(Pattern.matches(regex, str))
return true;
throw new Exception("Invalid Item format");
});
}
catch(Exception e){
log.error(e);
message = e;
}