java - Converting LinkedHashSet to ArrayList or just using ArrayList
问题描述
Consider the following code:
final Set<String> allPaths = new HashSet<String>();
for (final String path: paths) {
allPaths.add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));
MyData
is some class I should not touch. It should get an ArrayList
as an argument. Before this day, we used that way because we didn't care about the order, that is why we used Set
(so there will not be duplicated). But now, I would like to keep the order of the elements, so after some research, I found out that I can use the data structure LinkedHashSet
in order to do so. So I did:
final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
for (final String path: paths) {
allPaths .add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));
Problem is, I'm not sure how to convert LinkedHashSet
to ArrayList
. Also, I thought of using ArrayList
instead of LinkedHashSet
so I won't have to convert it, but I'll have to iterate over the array (O(n)
).
What good, clean and effiect way should I use?
解决方案
只需使用该public boolean addAll(Collection<? extends E> c)
方法,在 arrayList 上,它接受任何Collection
.
你有你的LinkedHashSet
:
final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
for (final String path: paths) {
allPaths .add(path);
}
然后执行(即使mylist
不为空,您也可以使用它):
List<String> myList = new ArrayList<>();
mylist.addAll(allPaths);
或者更简单的方法:
List<String> myList = new ArrayList<>(allPaths);
推荐阅读
- python - 在 Python 中为提取的单词创建表格 Yes/No 表
- node.js - 在猫鼬中创建新文档时可以添加新属性吗?
- reactjs - TypeError: this.props.loginActionCreater 不是 react-redux 中的函数
- css - Angular App 中的 Openlayers Fullscreen 在 Firefox 中有效,但在 Chrome 中无效
- python - 如何解决 ModuleNotFoundError:没有名为“_pywrap_tensorflow_internal”的模块?
- angular - 调整 Angular 5 代码以显示在手机上
- mysql - 基于日期的最后连续插入记录的计数
- r - GGP绘制在同一点结束的多条线
- amazon-web-services - 如何在 AWS ECS 中扩展任务/容器
- r - 基于经纬度的销售数据的交互式地图