[Libgdx] Sorting Vector2s by key.

Hi!

I have 50ish Vector2 representing the endpoint of a raycast and I’d like to arrange them by thier angle. This is for creating a light mesh so it means 50ish * number of lights.
Right now I’m using Java’s TreeMap to do so. I have a one map for each light. It works fine but I’m not sure if my method is correct.

Since the points change (wich means the angles change aswell) almost every update I constnalty have to clear the TreeMap, and fill it like this: map.put(angle, new Vector2(x, y)).
This way I have to create a lot of objects plus I’m not sure if the TreeMap is the best way to go here. Apparently I cant use a ‘temp’ Vector2 and just set a different value for it and add that to the map because it just discards it.
Thing is I’m not too familiar with the Maps of Java / Libgdx nor thier sorting performance.

My question is if there is a better Map or a better method to contain a bunch of Vector2s and sort them by thier angle.

Any help is much appreciated! :wink:

It’s probably better to just use a List (either ArrayList or (better yet) libGDX’s Array) and sort it whenever it needs sorted, unless for some reason you need it to be a tree. If you’re just iterating over the vecs in order, then a list structure is best.

EDIT: to also get the key-value map, simply have a separate hashmap for kv access, and use the Array for ordered access.

I calculate the angle early because it has to be associated with that given point thats why I thought a map would be the best.

[quote]map.put(angle, new Vector2(x, y))
[/quote]
If the angle can be calculated directly from the vector then it doesn’t need to be stored. (although if that computation is expensive it might be better to store it)

Otherwise you could use a Pair data type:

public class Pair<A, B> {
    public A a;
    public B b;

    public boolean equals(Object o) {
        return o != null && o instanceof Pair && a.equals(((Pair) o).a) && b.equals(((Pair) o).b);
    }
    // some hashCode method
    // some constructors
}

And have an Array of that, and sort whenever you change the data using a comparator that compares on the angle field.
This is again if you don’t actually need key-value access, but are only using the mapping for the sorting.