java - 检索插入顺序中的 LinkedHashSet 元素并将它们保存到局部变量中

标签 java arraylist collections set linkedhashset

我有一个 linkedhashset,我需要从中获取与插入元素相同的元素。 要检索,我无法按准确的插入顺序获取元素。

将 linkedHashset 转换为 List 以通过索引获取,但担心转换为 list 会打乱我的元素并改变顺序

  LinkedHashSet<String> personDetails = new LinkedHashSet<String>();
  //persondetails => John, kennedy, Female
  List<String> details = new ArrayList<>(personDetails);
  String firstName = details.get(0);
  String lastName = details.get(1);
  String gender = details.get(2);

转换为列表偏离了我的主要目标,即首先按插入顺序检索它们,因为列表不保留顺序。

你能给我建议一个替代方案还是我的错误吗?

最佳答案

首先,您无需将 LinkedHashSet 转换为 List 即可根据插入顺序检索它们。您可以使用迭代器迭代 Set。

例如:

Iterator<String> iter = personDetails.iterator();
String firstName = null;
if (iter.hasNext())
    firstName = iter.next();
String lastName = null;
if (iter.hasNext())
    lastName = iter.next();
String gender = null;
if (iter.hasNext())
    gender = iter.next();

其次,当您使用接受源 Collcetion 作为输入的构造函数创建 ArrayList 时,Collection 会按顺序迭代将元素添加到 ArrayList。迭代顺序取决于Collection 的迭代器的实现,在LinkedHashSet 的情况下,迭代顺序是插入的顺序。因此,您的 List 将保留插入顺序。

您可以在 Javadoc 中看到这一点:

java.util.ArrayList.ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

关于java - 检索插入顺序中的 LinkedHashSet 元素并将它们保存到局部变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502464/

相关文章:

.net-3.5 - 本地化 IEnumerable 的最佳方法是什么?

java - Amazon S3 AWS 出于未知原因开始给出错误代码 400

java - OpenCMS - 301 重定向

java - 错误 Kotlin 类型推断失败 预期类型不匹配 Map<MessageDestination, List<MessageSender>> 是预期的

java - 将两个数组列表合二为一

c# - 如何在程序退出时保存变量值?

Java:是否有一些工具能够将 X[][] 重构为 List<List<X>>?

c# - 如何在 C#.NET 中创建控件数组?

java - 无法将类型类 java.sql.Timestamp 转换为类 org.joda.time.DateTime

Java:从列表中删除单词