-1

I have a multimap which will contain bunch of keys and values in it.

private final Multimap<String, Process> processById = TreeMultimap.create();

Now for same key I can have bunch of Process so that's why I am using multimap here. Now I need to sort Process object in descending order of endTime in it. For each key in the map when I iterate the List<Process>, it should print process object in descending order of endTime. So I implemented Comparable interface here.

public final class Process implements Comparable<Process> {
  private final String clientId;
  private final long endTime;
  // .. more fields

  //... constructor, getters, toString methods

  @Override
  public int compareTo(Process o) {
    // is this logic right here?
    return Long.compare(this.endTime, o.endTime) * (-1);
  }
}

My question is - Is this the right way to do or my logic is wrong here?

Process process = getProcess(task);
String id = task.getId();
// populate multimap here
processById.put(id, process);
flash
  • 1,455
  • 11
  • 61
  • 132
  • Your code seem to work. Your logic seem OK too. Is there any problem with your code? – Liem Le Feb 06 '18 at 03:57
  • Multiplying by `-1` is the only option I have here to get this sorted in descending order or is there any other way? – flash Feb 06 '18 at 03:58
  • Multiplying by `-1` is equal to `Long.compare(o.endTime, this.endTime)`, so in your case I think it right. TreeMap does not let you put a `null` as a key. So your `compareTo` method is right too. If you may want to work with nullable container, you should consider to check null first. – Liem Le Feb 06 '18 at 04:02
  • I'm voting to close this question as off-topic because asking us to validate your expectation without having actually tried it is off-topic. You are expected to actually TRY your solution and ask questions when it doesn't meet your expectations. – Jim Garrison Feb 06 '18 at 05:33

1 Answers1

1

If you have to multiply by -1, better to just reverse the fields.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138