It looks like you are trying to fulfill Nearest Neighbor queries. This is where you try to find the point (or points) closest to another point. For a naive solution, you can simply save the list of points and drag them through the distance formula to find out which ones are closest. But if you want to execute queries faster, you will need to use a spatial data structure that allows you to perform such queries. I would suggest the KD tree. Java does not come with an implementation of KD Tree in its standard library, so you need to implement this yourself.
TreeMap is just an implementation of the Map interface, which allows you to add and retrieve values by their keys. If you want to write something to create a minimal spanning tree, you will need to do it yourself.
source share