I have the following problem regarding the correct use of streams and map.
The problem is the following
I have a method that reads a file from input and inserts record in a database, in a few words it performs some side effects
Furthermore, the same function returns some sort of a state, let's say a boolean (I have some degree of freedom about this) that states that the function went well.
public static boolean execute(String filename){
// Perform some side effects (e.g. write on DB)
return true; // or false according to some criteria;
}
Then, I have to call it with let's say two files and I have to detect if at least one went well (i.e. if at least one execution returned true)
My simple solution is: (a sort of simplified version of the command pattern)
public class Entrypoint {
public static boolean myFunction(String input) {
System.out.println("executed..." + input);
return !input.equals("B");
}
public static void main(String[] args) {
List<String> lst = Arrays.asList("A", "B", "C", "D", "E", "F");
long callsOk = lst.stream().map(Entrypoint::myFunction)
// .filter(x -> x.equals(true)).count();
.filter(x -> x).count(); // Better, as suggested by Donat
System.out.println("OK=" + callsOk);
}
}
This work, fine, the output is:
executed...A
executed...B
executed...C
executed...D
executed...E
executed...F
OK=5
That is right because it should fail (return false) for "B"
The question is:
Is it fine to use a function like myFunction:
- whose prime purpose is to perform side effects
and
- the purpose of its return value is just to give the status of the operation performed (success or not) and no other kind of data
inside a map in order to count the number of yields == true?
Or am I messing up, and there is a better solution to handle this?