如果我有一个集合,如集合<String> strs,我怎么能得到第一项?我可以调用一个迭代器,取它的第一个next(),然后丢弃迭代器。有没有更少浪费的方法呢?
当前回答
在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);
}
其他回答
Iterables。get (indexYouWant yourC)
因为实际上,如果你使用集合,你应该使用谷歌集合。
没有这样的东西作为“第一”项目在一个集合,因为它是…嗯,只是一个集合。
从Java文档的Collection.iterator()方法:
没有关于元素返回顺序的保证。
所以你不能。
如果使用其他接口,如List,可以执行以下操作:
String first = strs.get(0);
但直接从一个集合这是不可能的。
听起来你的Collection想要像list一样,所以我建议:
List<String> myList = new ArrayList<String>();
...
String first = myList.get(0);
在java 8中:
Optional<String> firstElement = collection.stream().findFirst();
对于旧版本的java,在Guava Iterables中有一个getFirst方法:
Iterables.getFirst(iterable, defaultValue)
Guava提供了一个onlyElement Collector,但只有在希望集合只有一个元素时才使用它。
Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())
如果不确定有多少元素,请使用findFirst。
Optional<String> optionalString = collection.stream().findFirst();
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?