java.util.NoSuchElementException - on iterating over sorted treemap

老子叫甜甜 提交于 2019-12-13 05:00:03

问题


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]

Goal

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

entriesSortedByValue

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;
    }

回答1:


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.



来源:https://stackoverflow.com/questions/26304796/java-util-nosuchelementexception-on-iterating-over-sorted-treemap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!