Reputation: 2659
I'm looping over my program, and for no certain reasons I've got the following error
Exception in thread "main" java.util.NoSuchElementException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
at java.util.TreeMap$KeyIterator.next(Unknown Source)
at EloRating.setNewSeason(EloRating.java:242)
This error points to the iterator loop.
TreeMap<String,Double> treeMap = new TreeMap<String,Double>();
for (Entry<String, Double> team : teamsIntersection.entrySet()) {
treeMap.put(team.getKey(), listTeams.get(team.getKey()).getRating());
}
SortedSet<Entry<String, Double>> listSorted = entriesSortedByValues(treeMap);
Iterator<Entry<String, Double>> iter = listSorted.iterator();
int stop = (amountOfIntersectTeams+1)/2;
for(int i = 0; i < (stop-1); i++){
-----------> iter.next();
}
double median = iter.next().getValue();
If I execute the program once, nothing special happens. But for some benchmark reasons I've to loop over the program 25.000 times with some slightly adjusted parameters. And when I try to start the program again with the parameters from after an error, it will go further. [At the moment of this error, iterator contained 10 values]
I want to have the upper median on the values of the Hashmap teamsIntersection. e.g. a-3 b-1 c-2 d-2 e-5 f-4 then I want the value of 3 back from a
static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
return e1.getValue().compareTo(e2.getValue());
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
Upvotes: 0
Views: 4583
Reputation: 198043
If you have multiple entries with the same value, they will get merged by the comparator you've written, since TreeSet
dedups elements relative to its comparator.
Assuming that amountOfIntersectTeams
is the size of the map you're dealing with, that's my best bet as to what's going on.
To fix it, I'd consider adding a secondary comparison of the keys in your Comparator
when the values compare as equal.
Upvotes: 2