The first option is to create a comparator and then sort the collection. I would do something like:
public static void main(String... arg) {
LinkedList<String> someStringList = new LinkedList<>();
someStringList.add("2");
someStringList.add("1");
System.out.println(someStringList);
Collections.sort(someStringList, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return theNodesDistance(s1).compareTo(theNodesDistance(s2));
}
});
System.out.println(someStringList);
}
public static Integer theNodesDistance(String str){
return Integer.parseInt(str); // here return the distance
}
Another option is to create a class Node with an id and distance:
public class Node implements Comparable<Node> {
String id;
Integer distance;
public Node(String id) {
this.id = id;
this.distance = theNodesDistance(id);
}
@Override
public int compareTo(Node node) {
return this.distance.compareTo(node.distance);
}
public String toString() {
return id;
}
public Integer theNodesDistance(String str){
return Integer.parseInt(str);
}
}
Then, sort your list doing:
LinkedList<Node> nodes = new LinkedList<>();
nodes.add(new Node("2"));
nodes.add(new Node("1"));
System.out.println(nodes);
Collections.sort(nodes);
System.out.println(nodes);
Finally, you can use a PriorityQueue which organizes the elements whenever you insert a new node. I mean, you can remove each node in order.
Queue<Node> nodes = new PriorityQueue<>();
nodes.add(new Node("10"));
nodes.add(new Node("3"));
nodes.add(new Node("2"));
nodes.add(new Node("1"));
nodes.add(new Node("4"));
System.out.println(nodes.remove());
System.out.println(nodes.remove());
System.out.println(nodes.remove());
System.out.println(nodes.remove());
System.out.println(nodes.remove());
In this case, the output will be:
1
2
3
4
10