Good way to get *any* value from a Java Set?(从 Java Set 中获取 *any* 值的好方法?)
问题描述
给定一个简单的 Set<T>,从 Set 获取 any 值的好方法是什么(快速,几行代码)代码>?
Given a simple Set<T>, what is a good way (fast, few lines of code) to get any value from the Set?
有了List,很简单:
List<T> things = ...;
return things.get(0);
但是,对于 Set,没有 .get(...) 方法,因为 Set 没有顺序.
But, with a Set, there is no .get(...) method because Sets are not ordered.
推荐答案
一个 Set 是一个 Iterable,所以迭代到第一个元素是可行的:
A Set<T> is an Iterable<T>, so iterating to the first element works:
Set<T> things = ...;
return things.iterator().next();
Guava 有 一种方法 来做到这一点,虽然上面的代码片段 可能更好.
Guava has a method to do this, though the above snippet is likely better.
这篇关于从 Java Set 中获取 *any* 值的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Java Set 中获取 *any* 值的好方法?
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
