java hash set demo
HashSet is a data collection with unique elements. If you try to add an element that is already exist in the collection, it will be ignored. The demo below moves an array of strings with duplicates to a hashset, the duplicates are gone in the hashset.
[code language=”java”]
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
String[] strArr = {"aaa", "bbb", "ccc", "aaa", "ddd", "ccc", "eee"};
HashSet<String> hashedStrList = new HashSet<String>();
System.out.println("Original string list, with deplicates:");
for (String str : strArr) {
System.out.println(str);
hashedStrList.add(str);
}
System.out.println("Hashed string list, no duplicates:");
for (String str : hashedStrList) {
System.out.println(str);
}
}
}
[/code]
Output:
[code language=”text”]
Original string list, with deplicates:
aaa
bbb
ccc
aaa
ddd
ccc
eee
Hashed string list, no duplicates:
aaa
ccc
bbb
eee
ddd
[/code]
Search within Codexpedia
Search the entire web