Reputation: 61
Do you think it would be possible to implement sparse matrix operations using the new Stream interface in Java 1.8 ? If yes, how do we need to implement the matrixes and the operations. Clearly, I am looking for it for being able eventually to use the "automatic" parallelization.
Upvotes: 4
Views: 1053
Reputation: 3877
It can clearly be done. How about something like below for a simple SPMV (Sparse matrix vector multiplication), with the sparse matrix represented in the coordinate COO format (the simplest sparse format out there):
class COO {
int x, y, value;
}
public static ArrayList<Integer> spmv(List<COO> values, ArrayList<Integer> v) {
final ArrayList<Integer> result = new ArrayList<>(Collections.nCopies(v.size(), 0));
values.stream().forEach(
coo -> result.set(coo.x, result.get(coo.x) + coo.value * v.get(coo.y))
);
return result;
}
But I sincerely suggest you use something pre-coded, if you don't want to spend the next 3 years of your life understanding the performance implications of sparse matrix operations. This is quite a large research/optimisation topic and there are many factors to consider like (just off the top of my head):
There are many implementations out there that can achieve orders of magnitude improvements in performance versus hand crafted implementation. To name a few, check out:
I would just write bindings to those if they don't exist already, although something like la4j looks quite promising.
Upvotes: 2