使用HashSet過濾掉重複的字符

利用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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章