为了避免集合中出现重复元素,您不需要使用
List
,而需要使用
Set
(例如
HashSet
)。
如果您想保留添加
String
的顺序,请使用
LinkedHashSet
。
最后,如果您希望您的
Set
自然排序您的
String
(或能够使用
Comparator
对其进行排序),请使用
TreeSet
。
示例String foo = "ghghababcdef";
Set<String> hash = new HashSet<>();
Set<String> linked = new LinkedHashSet<>();
Set<String> tree = new TreeSet<>();
for (char c: foo.toCharArray()) {
hash.add(Character.toString(c));
linked.add(Character.toString(c));
tree.add(Character.toString(c));
}
System.out.println(hash);
System.out.println(linked);
System.out.println(tree);
输出
[a, b, c, d, e, f, g, h] // this may vary
[g, h, a, b, c, d, e, f] // keeps insertion order
[a, b, c, d, e, f, g, h] // sorted lexicographically by default
Set
来实现内容的唯一性。 - Konstantin Yovkov