Java 在 ArrayList 中保存唯一字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2235471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save a list of unique Strings in the ArrayList
提问by EugeneP
I read data from a text file, so there may be:
我从文本文件中读取数据,所以可能有:
John Mary John Leeds
I now need to get 3 unique elements in the ArrayList, because there are only 3 unique values in the file output (as above).
我现在需要在 ArrayList 中获取 3 个唯一元素,因为文件输出中只有 3 个唯一值(如上)。
I can use a HashTable and add information to it, then simply copy its data into the List. Are there other solutions?
我可以使用 HashTable 并向其添加信息,然后只需将其数据复制到 List 中。还有其他解决方案吗?
采纳答案by Adamski
Why do you need to store it in a List
? Do you actually require the data to be ordered or support index-based look-ups?
为什么你需要把它存储在一个List
? 您是否真的需要对数据进行排序或支持基于索引的查找?
I would suggest storing the data in a Set
. If ordering is unimportant you should use HashSet
. However, if you wish to preserve ordering you could use LinkedHashSet
.
我建议将数据存储在Set
. 如果排序不重要,则应使用HashSet
. 但是,如果您希望保留顺序,您可以使用LinkedHashSet
.
回答by Chandra Sekar
You can check list.contains()before adding.
您可以在添加之前检查list.contains()。
if(!list.contains(value)) {
list.add(value);
}
I guessed it would be obvious! However, adding items to a HashSet and then creating a list from this set would be more efficient.
我猜这会很明显!但是,将项目添加到 HashSet 然后从该集合创建列表会更有效。
回答by Tom Duckering
Use a set
instead of a list. Take a look at here: Java Collections Tutorialsand specifically about Sets here: Java Sets Tutorial
使用一个set
而不是一个列表。看看这里:Java 集合教程,特别是这里的集合:Java 集合教程
In a nutshell, sets contain one of something. Perfect :)
简而言之,集合包含某物之一。完美的 :)
回答by Fabian Steeg
If you have a List
containing duplicates, and you want a List
without, you could do:
如果你有一个List
包含重复项,而你想要一个List
没有,你可以这样做:
List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));
That is, wrap the old list into a set to remove duplicates and wrap that set in a list again.
也就是说,将旧列表包装成一个集合以删除重复项并再次将该集合包装在一个列表中。
回答by djangofan
Here is how I solved it:
这是我解决它的方法:
import groovy.io.*;
def arr = ["5", "5", "7", "6", "7", "8", "0"]
List<String> uniqueList = new ArrayList<String>(new HashSet<String>( arr.asList() ));
System.out.println( uniqueList )
回答by Erol
class HashSetList<T extends Object>
extends ArrayList<T> {
private HashSet<Integer> _this = new HashSet<>();
@Override
public boolean add(T obj) {
if (_this.add(obj.hashCode())) {
super.add(obj);
return true;
}
return false;
}
}
I now use those kind of structure for little programs, I mean you have little overhead in order to have getters and setters but uniqueness. Moreover you can override hashCode
to decide wether your item equals another one.
我现在将这种结构用于小程序,我的意思是你有很少的开销来拥有 getter 和 setter,但具有独特性。此外,您可以覆盖hashCode
以决定您的项目是否等于另一个项目。