Sort objects in a set by separate parameter instead of key

  Kiến thức lập trình

Given a class called “SortableRecord” that has an ID to determine uniqueness in the set and a value to determine the order in the set, how can I achieve the following:

SortedSet<SortableRecord> coll = new TreeSet<>();
coll.add(new SortableRecord("a", 10.0));
coll.add(new SortableRecord("a", 11.0));
coll.add(new SortableRecord("a", 300.0));
coll.add(new SortableRecord("b", 11.0));
coll.add(new SortableRecord("b", 41.0));

assertEquals(2, coll.size());

There should only be two objects in the set. The object with ID b should come first as its value is 41 and object a ID is 300.

LEAVE A COMMENT