利用HashSet不允许存在重复元素的特性,可以实现对重复元素的过滤。
public static void main(String[] args) {
String[] str = { "a", "b", "c", "d", "b", "a" };
// 方法1
Set<String> hashSet = new HashSet<String>();
hashSet.addAll(Arrays.asList(str));
String[] result = hashSet.toArray(new String[0]);
for (String string : result) {
System.out.print(string + " ");
}
System.out.println();
// 方法2
Iterator<String> i = new HashSet<String>(Arrays.asList(str)).iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
}
运行结果:
d b c a
d b c a