Java:从集合中获取第一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1671378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Get first item from a collection
提问by Nick Heiner
If I have a collection, such as Collection<String> strs
, how can I get the first item out? I could just call an Iterator
, take its first next()
, then throw the Iterator
away. Is there a less wasteful way to do it?
如果我有一个集合,例如Collection<String> strs
,我怎样才能取出第一个项目?我可以只调用 an Iterator
,先拿走它next()
,然后扔掉它Iterator
。有没有一种不那么浪费的方法呢?
采纳答案by Carl
Iterables.get(yourC, indexYouWant)
Iterables.get(yourC, indexYouWant)
Because really, if you're using Collections, you should be using Google Collections.
因为实际上,如果您使用的是收藏夹,则应该使用 Google 收藏夹。
回答by OscarRyz
There is no such a thing as "first" item in a Collection
because it is .. well simply a collection.
在 a 中没有“第一”项这样的东西,Collection
因为它只是一个集合。
From the Java doc's Collection.iterator()method:
来自 Java 文档的Collection.iterator()方法:
There are no guarantees concerning the order in which the elements are returned...
没有关于元素返回顺序的保证......
So you can't.
所以你不能。
If you use anotherinterface such as List, you can do the following:
如果您使用其他接口,例如List,您可以执行以下操作:
String first = strs.get(0);
But directly from a Collection this is not possible.
但是直接从 Collection 中这是不可能的。
回答by Andy Gherna
You could do this:
你可以这样做:
String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];
The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:
Collection 的 javadoc 给出了以下注意事项 wrt 数组元素的排序:
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
如果此集合对其迭代器返回其元素的顺序做出任何保证,则此方法必须以相同的顺序返回元素。
回答by jheddings
Looks like that is the best way to do it:
看起来这是最好的方法:
String first = strs.iterator().next();
Great question... At first, it seems like an oversight for the Collection
interface.
好问题... 乍一看,这似乎是对Collection
界面的疏忽。
Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item)
call, since the order isn't necessarily preserved.
请注意,“first”并不总是返回您放入集合中的第一件事,并且可能仅对有序集合有意义。也许这就是为什么没有get(item)
调用的原因,因为不一定要保留顺序。
While it might seem a bit wasteful, it might not be as bad as you think. The Iterator
really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator
object, but that is really the only overhead (not like copying all the elements).
虽然它可能看起来有点浪费,但它可能没有你想象的那么糟糕。该Iterator
真的只是包含索引信息到集合,而不是通常的整个集合的副本。调用这个方法会实例化Iterator
对象,但这确实是唯一的开销(不像复制所有元素)。
For example, looking at the type returned by the ArrayList<String>.iterator()
method, we see that it is ArrayList::Itr
. This is an internal class that just accesses the elements of the list directly, rather than copying them.
例如,查看ArrayList<String>.iterator()
方法返回的类型,我们看到它是ArrayList::Itr
。这是一个内部类,它只是直接访问列表的元素,而不是复制它们。
Just be sure you check the return of iterator()
since it may be empty or null
depending on the implementation.
请务必检查返回,iterator()
因为它可能为空或null
取决于实现。
回答by James Black
If you know that the collection is a queue then you can cast the collection to a queue and get it easily.
如果您知道该集合是一个队列,那么您可以将该集合转换为一个队列并轻松获取它。
There are several structures you can use to get the order, but you will need to cast to it.
您可以使用多种结构来获取订单,但您需要对其进行强制转换。
回答by Jim Ferrans
It sounds like your Collection wants to be List-like, so I'd suggest:
听起来你的收藏想要像列表一样,所以我建议:
List<String> myList = new ArrayList<String>();
...
String first = myList.get(0);
回答by Vitalii Fedorenko
In java 8:
在 Java 8 中:
Optional<String> firstElement = collection.stream().findFirst();
For older versions of java, there is a getFirst method in Guava Iterables:
对于旧版本的 java,在 Guava Iterables 中有一个 getFirst 方法:
Iterables.getFirst(iterable, defaultValue)
回答by Sindhoo Oad
It totally depends upon which implementation you have used, whether arraylist linkedlist, or other implementations of set.
这完全取决于您使用了哪种实现,无论是 arraylist 链表还是 set 的其他实现。
if it is set then you can directly get the first element , their can be trick loop over the collection , create a variable of value 1 and get value when flag value is 1 after that break that loop.
如果设置了,那么您可以直接获取第一个元素,它们可以在集合上进行技巧循环,创建一个值为 1 的变量,并在中断该循环后标志值为 1 时获取值。
if it is list's implementation then it is easy by defining index number.
如果它是列表的实现,那么通过定义索引号很容易。
回答by paul
In Java 8 you have some many operators to use, for instance limit
在 Java 8 中,您可以使用许多运算符,例如limit
/**
* Operator that limit the total number of items emitted through the pipeline
* Shall print
* [1]
* @throws InterruptedException
*/
@Test
public void limitStream() throws InterruptedException {
List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
.stream()
.limit(1)
.collect(toList());
System.out.println(list);
}
回答by Nacho Soriano
You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:
你可以做一个铸造。例如,如果存在一个具有此定义的方法,并且您知道此方法正在返回一个列表:
Collection<String> getStrings();
And after invoke it, you need the first element, you can do it like this:
在调用它之后,你需要第一个元素,你可以这样做:
List<String> listString = (List) getStrings();
String firstElement = (listString.isEmpty() ? null : listString.get(0));