public class TestHashSet
1: //TestHashSet.java
3: import java.util.ArrayList;
4: import java.util.HashSet;
5: import java.util.Iterator;
7: public class TestHashSet
8: {
9: public static void main(String[] args)
10: {
11: //Create an array of char to contain the characters
12: //of "Hello, world!" and then display them.
13: System.out.println("1==============================");
14: String s = "Hello, world!";
15: char[] sChars = s.toCharArray();
16: for (char c : sChars)
17: {
18: System.out.print(c);
19: }
20: System.out.println();
21: System.out.println(sChars);
22: System.out.println(sChars.length);
24: //Create an ArrayList of Character to contain the
25: //characters of "Hello, world!" and then display them.
26: System.out.println("2==============================");
27: ArrayList<Character> arrayList = new ArrayList<>();
28: for (char c : sChars)
29: {
30: arrayList.add(c);
31: }
32: for (char c : arrayList)
33: {
34: System.out.print(c);
35: }
36: System.out.println();
37: System.out.println(arrayList);
38: System.out.println(arrayList.size());
40: //Can't use sChars in place of arrayList in the following
41: //HashSet constructor because it's not a "container of objects".
42: System.out.println("3==============================");
43: HashSet<Character> myHashSet = new HashSet<Character>(arrayList);
44: for (char c : myHashSet)
45: {
46: System.out.print(c);
47: }
48: System.out.println();
49: System.out.println(myHashSet);
50: System.out.println(myHashSet.size());
52: //Display the HashSet using an Iterator.
53: System.out.println("4==============================");
54: Iterator<Character> cIter = myHashSet.iterator();
55: while (cIter.hasNext())
56: {
57: System.out.print(cIter.next());
58: }
59: System.out.println();
60: System.out.println(myHashSet.size());
62: //Display the HashSet using a Stream and a lambda functions.
63: System.out.println("5==============================");
64: myHashSet.stream().forEach(c -> System.out.print(c));
65: System.out.println();
66: System.out.println(myHashSet.size());
68: //Display the HashSet using a Stream and a method reference.
69: System.out.println("6==============================");
70: myHashSet.stream().forEach(System.out::print);
71: System.out.println();
72: System.out.println(myHashSet.size());
73: }
74: }
75: /* Output:
76: 1==============================
77: Hello, world!
78: Hello, world!
79: 13
80: 2==============================
81: Hello, world!
82: [H, e, l, l, o, ,, , w, o, r, l, d, !]
83: 13
84: 3==============================
85: !deHl,orw
86: [ , !, d, e, H, l, ,, o, r, w]
87: 10
88: 4==============================
89: !deHl,orw
90: 10
91: 5==============================
92: !deHl,orw
93: 10
94: 6==============================
95: !deHl,orw
96: 10
97: */