The task is to get all the lines from the file except the lines starting with #, using only the cactoos library. I got the following solution:
Iterable<Text> data =
new Filtered(
(Func<Text, Boolean>) text -> !text.asString().startsWith("#"),
new Split(
new TextOf(file),
new TextOf("\\n")
)
);
In this solution, I do not like the filtering function, in which I use the startsWith
method directly. In cactoos, I did not find a single object that checks that a string begins with a character. And the startsWith
call violates the principle of elegant objects, that everything should be an object.
One of the solutions that I see is to write an object like
import org.cactoos.Scalar;
import org.cactoos.Text;
import org.cactoos.text.TextOf;
public final class StartsWith implements Scalar<Boolean> {
private final Text origin;
private final Text prefix;
public StartsWith(String origin, String prefix) {
this(new TextOf(origin), new TextOf(prefix));
}
public StartsWith(Text origin, Text prefix) {
this.origin = origin;
this.prefix = prefix;
}
@Override
public Boolean value() throws Exception {
return origin.asString().startsWith(prefix.asString());
}
}
Is it possible to do this with only the cactoos library classes?
Which solution would you prefer?