{"record":{"id":"868a0c98693974a4","repo":"alibaba/nacos","slug":"expected-one-element-but-was","errorCode":null,"errorMessage":"expected one element but was: <{}>","messagePattern":"expected one element but was: <(.+?)>","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"warning","filePath":"common/src/main/java/com/alibaba/nacos/common/utils/CollectionUtils.java","lineNumber":316,"sourceCode":"    \n    /**\n     * return the first element, if the iterator contains multiple elements, will throw {@code\n     * IllegalArgumentException}.\n     *\n     * @throws NoSuchElementException   if the iterator is empty\n     * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the iterator is\n     *                                  unspecified.\n     */\n    public static <T> T getOnlyElement(Iterable<T> iterable) {\n        if (iterable == null) {\n            throw new IllegalArgumentException(\"iterable cannot be null.\");\n        }\n        Iterator<T> iterator = iterable.iterator();\n        T first = iterator.next();\n        if (!iterator.hasNext()) {\n            return first;\n        }\n        throw new IllegalArgumentException(buildExceptionMessage(iterator, first));\n    }\n    \n    private static <T> String buildExceptionMessage(Iterator<T> iterator, T first) {\n        StringBuilder msg = new StringBuilder();\n        msg.append(\"expected one element but was: <\");\n        msg.append(first);\n        for (int i = 0; i < 4 && iterator.hasNext(); i++) {\n            msg.append(\", \");\n            msg.append(iterator.next());\n        }\n        if (iterator.hasNext()) {\n            msg.append(\", ...\");\n        }\n        msg.append('>');\n        return msg.toString();\n    }\n    \n    /**","sourceCodeStart":298,"sourceCodeEnd":334,"githubUrl":"https://github.com/alibaba/nacos/blob/9b989acdf181d00898f2e8839257bb2b2a3cefe3/common/src/main/java/com/alibaba/nacos/common/utils/CollectionUtils.java#L298-L334","documentation":"Thrown by CollectionUtils.getOnlyElement(Iterable) when the iterable is non-null and contains more than one element. The message is built by buildExceptionMessage and lists up to 5 of the offending elements followed by '...' if there are more. It enforces a single-element contract.","triggerScenarios":"Calling getOnlyElement on a collection that legitimately has 2+ elements when the caller assumed uniqueness — e.g., a query expected to match one record but matched several.","commonSituations":"A lookup/filter that should return exactly one result but the filter is too loose (duplicate config keys, multiple instances matching, ambiguous mapping).","solutions":["Tighten the upstream query/filter so it yields exactly one element.","If multiple results are valid, use iterable.iterator().next() or pick by a deterministic tie-breaker instead of getOnlyElement.","Log the element list from the exception message to see what duplicates exist."],"exampleFix":"// before\nT only = CollectionUtils.getOnlyElement(results);\n\n// after\nif (results.size() == 1) {\n    T only = results.iterator().next();\n} else {\n    // handle ambiguity explicitly\n    throw new AmbiguousResultException(results);\n}","handlingStrategy":"validation","validationCode":"if (iterable == null) return null;\nint size = (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : -1;\nif (size == 1) {\n    return ((Collection<T>) iterable).iterator().next();\n}\n// size != 1 -> do not call getOnlyElement\nreturn null; // or throw a domain-specific exception","typeGuard":null,"tryCatchPattern":"try {\n    return CollectionUtils.getOnlyElement(iterable);\n} catch (IllegalArgumentException e) {\n    // more than one element — e.getMessage() lists them\n    throw new AmbiguousResultException(e.getMessage());\n}","preventionTips":["Ensure the source query yields exactly one element before calling getOnlyElement.","When duplicates are possible, use iterator().next() with explicit disambiguation."],"tags":["collections","cardinality","validation","utility"],"backgroundTag":null,"analyzedSha":"9b989acdf181d00898f2e8839257bb2b2a3cefe3","analyzedAt":"2026-08-14T07:17:31.569Z","schemaVersion":2},"datasetVersion":"2026-08-14T10:17:34.591Z"}