Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从集合中获取第一个(也是唯一的值)_Java_Collections - Fatal编程技术网

Java 从集合中获取第一个(也是唯一的值)

Java 从集合中获取第一个(也是唯一的值),java,collections,Java,Collections,可能重复: 在Java中,我经常遇到一个只有一个元素的集合,我需要检索它。因为集合不能保证一致的排序,所以没有first()或get(int-index)方法,所以我需要使用一些非常难看的东西,例如: public Integer sillyExample(Collection<Integer> collection){ if(collection.size()==1){ return collection.iterator().next(); }

可能重复:

在Java中,我经常遇到一个只有一个元素的集合,我需要检索它。因为集合不能保证一致的排序,所以没有
first()
get(int-index)
方法,所以我需要使用一些非常难看的东西,例如:

public Integer sillyExample(Collection<Integer> collection){
    if(collection.size()==1){
        return collection.iterator().next();
    }
    return someCodeToDecideBetweenElements(collection);
}
public Integer silly示例(集合){
if(collection.size()==1){
返回集合.iterator().next();
}
返回SomeCodeToDecidebetween元素(集合);
}
那么,如何才能得到唯一的元素呢?我不敢相信没有更好的方法

请注意,我理解没有“第一”的概念,我只是在知道迭代器中只有一个元素时,试图避免构建迭代器


编辑:彼得·伍斯特发现了一个非常类似的问题。我之所以不讨论这个问题,是因为我不想得到“first”元素,这意味着一个一致的排序,而是在检查它确实是唯一的元素之后得到“one and only”元素。

最简单的答案就是你所做的

first = collection.iterator().next();

注意迭代器()是一个方法,这是一个输入错误吗?

你看过谷歌番石榴吗?如果您知道集合只有一个元素,则可以使用
Iterables.getOnlyElement(collectionWithOneElement)
但是如果您不知道但仍然只需要第一个元素,那么可以使用
getFirst(Iterable,t default)
。如果它为空,它还将返回您定义的默认值。

它很简单

 Iterator<Integer> itr = collection.iterator(); 
 Object firstObj = itr.hasNext()? itr.next() : null;
Iterator itr=collection.Iterator();
对象firstObj=itr.hasNext()?itr.next():null;

与此完全相同,只是我不敢调用
size()
Iterator it=collection.Iterator();返回它。hasNext()?it.next():null
现在您可以使用更通用的
Iterable
。实际上,
Collection
不提供
first()
get(int)
,这是一件好事,因为集合通常是无序的,并且没有“first”元素关于这个主题有一篇老文章:我会像上面Marko Topolnic的评论那样,只使用一个通用的方法签名。还要考虑到“构建迭代器”并不是一个好的范例:迭代器是一个非常轻量级的对象,可以随意创建,对性能的影响可以忽略不计。谢谢!我不知道这个方法,但我只是检查了它,它在内部执行
返回iterators.getOnlyElement(iterable.iterator())所以它仍然在内部构建一个迭代器…它对迭代器的作用也是完全可以预测的,就像我在问题下面的评论中所说的那样。这可能会让你放心,这种方法是最好的。谢谢彼得!是的,我忘记了迭代器中的()现在修正了。为什么被接受的答案不包括问题的“唯一价值”部分?