如果我有一个集合,如集合<String> strs,我怎么能得到第一项?我可以调用一个迭代器,取它的第一个next(),然后丢弃迭代器。有没有更少浪费的方法呢?
当前回答
Iterables。get (indexYouWant yourC)
因为实际上,如果你使用集合,你应该使用谷歌集合。
其他回答
Iterables。get (indexYouWant yourC)
因为实际上,如果你使用集合,你应该使用谷歌集合。
你可以选角。例如,如果存在一个具有此定义的方法,并且您知道该方法将返回一个List:
Collection<String> getStrings();
调用它之后,你需要第一个元素,你可以这样做:
List<String> listString = (List) getStrings();
String firstElement = (listString.isEmpty() ? null : listString.get(0));
Guava提供了一个onlyElement Collector,但只有在希望集合只有一个元素时才使用它。
Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())
如果不确定有多少元素,请使用findFirst。
Optional<String> optionalString = collection.stream().findFirst();
在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);
}
这完全取决于你使用的是哪种实现,是arraylist linkedlist,还是set的其他实现。
如果它被设置了,那么你可以直接获得第一个元素,它们可以在集合上进行诡计循环,创建一个值为1的变量,当标志值为1时获得值,然后打破循环。
如果是列表的实现,那么通过定义索引号很容易。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 如何检查IEnumerable是否为空或空?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder