从地图中删除键集值时获取 UnSupportedOperationException

Getting UnSupportedOperationException when removing keyset values from a map

我有下面这个方法,它遍历地图并根据特定条件删除数据。

private Map<String, String> getSearchResultsWithoutOverUsedData(
    Map<String, String> searchDocumentResults
) {
    List<String> overUsedTestData = this.extractOverUsedTestData(
        searchDocumentResults
    );

    if (overUsedTestData.size() > 0) {
        this.deleteSearchResultsAboveThresholdUsage(overUsedTestData);
        searchDocumentResults.keySet().removeAll(overUsedTestData);
    }
    return searchDocumentResults;
}

执行searchDocumentResults.keySet().removeAll(overUsedTestData);行时,有时会抛出以下错误。

java.lang.UnsupportedOperationException: null
    at java.util.Collections$UnmodifiableCollection.removeAll(Collections.java:1070) ~[?:1.8.0_302]
    at TestDataHandler.getSearchResultsWithoutOverUsedData(TestDataHandler.java:55) ~[MyService-1.0.jar:?]

由于参数 searchDocumentsResults 不是最终的,我很困惑为什么它是不可变的。任何有助于理解这一点的帮助将不胜感激。提前致谢。

如果 searchDocumentResults 映射碰巧是不可变的,您应该先创建它的副本,然后删除 overUsedTestData:

searchDocumentResults = new HashMap<>(searchDocumentResults);
searchDocumentResults.keySet().removeAll(overUsedTestData);

或使用流 API:

searchDocumentResults = searchDocumentResults.entrySet()
        .stream()
        .filter(e -> !overUsedTestData.contains(e.getKey()))
        .collect(Collectors.toMap(
            Map.Entry::getKey,
            Map.Entry::getValue
        ));