1

I am turning a HashSet of user-defined objects into an ArrayList of those same objects, i.e. like this:

List<MyObject> myList = new ArrayList<>(myMap.keySet())

I would like to sort this list so that the ordering is the same each time I compile my code.

But, importantly, I don't actually care how these objects are ordered. Therefore I would prefer not to define a Comparator, or have MyObject implement Comparable, if possible. What is the most lightweight way of doing this?

asked Jun 17, 2020 at 11:27
11
  • 1
    What's more lightweight than using a comparator like Collections.sort(myList, Comparator.comparing(MyObject::hashCode))? Commented Jun 17, 2020 at 11:31
  • 2
    What do you mean with "each time I compile my code"? Compiling the code has no influence here. Apparently, you mean running the code. Commented Jun 17, 2020 at 11:31
  • 2
    @daniu there is no guaranty that this produces the same order on each run. Commented Jun 17, 2020 at 11:32
  • 1
    Just out of curiosity, why do want to do that? Commented Jun 17, 2020 at 11:33
  • 3
    It’s important to know whether this is about multiple executions of this code within the same runtime or multiple executions of the program, i.e. in different JVM instances. In the latter case, "same ordering" needs a definition of "same object" first. Without these clarifications, the question is unanswerable. Commented Jun 17, 2020 at 11:40

1 Answer 1

3

But, importantly, I don't actually care how these objects are ordered.

This is exactly what Guava's Ordering.arbitrary() will do:

Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality). There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM.

However, it specifically doesn't support your requirement for:

I would like to sort this list so that the ordering is the same each time I compile my code.

For that, you'll need to give your objects some kind of identifying state. This could be name, an index of construction order or an explicit order. There is no general way to carry the "same" order across runs without knowing more about your code.

If the "same" order means the order in which your algorithm produced its results, make the Map one that preserves the order of insertion, rather than sorting afterwards. That will give you a deterministic order based on your code's behaviour.

answered Jun 17, 2020 at 11:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.