This question already has answers here:
The correct way to return the only element from a set
                                
                                    (5个答案)
                                
                        
                2年前关闭。
            
        

我有一组字符串:HashSet<String> idSet。如果集合中只有一个元素,我想提取字符串。这就是我在做什么:

if(idSet.size() == 1) {
    String id = (String) idSet.toArray()[0];
}


如果仅存在一个元素,这是获取字符串的正确方法吗?我想检查是否有更优雅的方法。

最佳答案

没有理由将整个集合转换为数组只是为了从中获取一个元素。相反,我将使用其迭代器:

if (idSet.size() == 1) {
    String id = idSet.iterator().next();
}

10-02 05:20