kaann45
kaann45

Reputation: 31

Sorting a LinkedList by value

I have a linkedlist structure and every nodes store the int ID number ,string name variable and Node link variable. I want to sort this list increasing order according to ID. Is the collection.sort suitable for this? How can I handle practically?

Upvotes: 0

Views: 68

Answers (1)

JMax
JMax

Reputation: 1202

You have two alternatives:

  1. Let your Node class implements the Comparable interface and implement the compareTo(NodeType other) like this: return Integer.compare(this.id, other.id).

  2. Use Collections.sort on your LinkedList with a custom Comparator: Collections.sort(list, (a,b) -> Integer.compare(a.getId(),b.getId()).

Upvotes: 1

Related Questions