I have this below piece of method that iterates through a map and removes data based on certain criteria.
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;
}
When the line searchDocumentResults.keySet().removeAll(overUsedTestData);
gets executed, it throws the following error sometimes.
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:?]
As the parameter searchDocumentsResults is not final, I'm confused why its immutable. Any help to understand this would be much appreciated. Thanks in advance.
CodePudding user response:
If searchDocumentResults
map happens to be immutable, you should create its copy first and then remove the overUsedTestData
:
searchDocumentResults = new HashMap<>(searchDocumentResults);
searchDocumentResults.keySet().removeAll(overUsedTestData);
or using Stream API:
searchDocumentResults = searchDocumentResults.entrySet()
.stream()
.filter(e -> !overUsedTestData.contains(e.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));