The javadoc says that.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))
But again, this is not necessary. What it is necessary is to override the method public boolean equals(Object entry)
for the method contains()
to work, instead you are declaring the method public boolean equals(Entry entry)
.
You should have an equals()
similar to.
@Override
public boolean equals(Object entry) {
if (entry instanceof Entry) return this.key == ((Entry) entry).key;
else return false;
}
Another thing to consider it that it is a terrible idea to mutate the object when this is already in a sorted/hashed collection. This will cause strange behavior. I'll show you an example.
Using this a toString()
method in your entry.
@Override
public String toString() {
return String.format("{ %d, %d }", key, value);
}
Using this code to print the priority queue.
PriorityQueue<Entry> queue = new PriorityQueue<>();
for (Entry data : entries) {
Entry entry = new Entry(data.getKey(), data.getValue());
if (queue.contains(entry)) {
for (Entry current : queue) { // just for the example
if (current.equals(entry)) {
current.addToValue(entry.getValue());
}
}
} else {
queue.add(entry);
}
}
while (!queue.isEmpty()) // print ordered
System.out.println(queue.poll());
With this data.
List<Entry> entries = Arrays.asList(
new Entry(1, 4),
new Entry(2, 3),
new Entry(2, 5)
);
The output is not correctly sorted { 1, 4 }, { 2, 8 }
instead { 2, 8 }, { 1, 4 }
, this because the entry with id 2 was mutated after it was added to the collection.
By the other hand, with this data
List<Entry> entries = Arrays.asList(
new Entry(1, 4),
new Entry(2, 8)
);
It prints the output correctly sorted { 2, 8 }, { 1, 4 }
.
The solution could be using a HashMap and then a TreeSet.
Map<Integer, Integer> map = new HashMap<>();
for (Entry data : entries) { // here instead read from csv and create entry
map.computeIfPresent(data.getKey(), (k, v) -> v + data.getValue()); // sum priorities
map.putIfAbsent(data.getKey(), data.getValue()); // add when not exists
}
Now that you have a map identified by the key and containing the sumarized values of the priorities, you can use a TreeSet or a PriorityQueue to sort the entries.
You don't need to use your custom Entry, you can use the java Entry and pass a Comparator to the TreeSet / PriorityQueue.
TreeSet<Map.Entry<Integer, Integer>> treeSet = new TreeSet<>((e1, e2) ->
e2.getValue() - e1.getValue() != 0 ?
e2.getValue() - e1.getValue() :
e2.getKey() - e1.getKey());
treeSet.addAll(map.entrySet());
System.out.println(treeSet);
This comparator compares first the priority, if is different, return -1 or 1, following a descendant order.
If the priority is the same, it compares the key, and returns -1 or 1 (0 is not possible because there are not duplicate keys) and order of the keys is descending.