How to sort a collection using comparator and a parameter in Java 8?
Here is a piece of code:
List<Point> sortedNeurons = neurons.parallelStream()
.sorted((n1, n2) -> Double.compare(
n1.getEuclideanDistanceFrom(inputVector),
n2.getEuclideanDistanceFrom(inputVector)))
.collect(Collectors.toList());
You are given a parameter inputVector that can be passed to a function that returns a primitive double value. If applied to an element of the collection, it returns some number. I want the collection to be ordered by this value. Something like: select id from neurons order by getEuclideanDistanceFrom(inputVector, id);
There are three problems here:
- nx.getEuclideanDistanceFrom(inputVector) gets repeated twice.
- I would like to use natural ordering of a double type, without declaring it, just like in an SQL query, when using order by clause.
- Perhaps n1, n2 -> n1, n2 could be substituted with a double colon :: notation.
P.S. I have a strong feeling that it can be fixed using something like bifunction or biconsumer... but couldn't figure it out...