1
22
23 package com.liferay.portal.kernel.util;
24
25 import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
26
27 import java.io.File;
28 import java.io.FileReader;
29 import java.io.IOException;
30
31 import java.util.Collection;
32 import java.util.Enumeration;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Set;
37
38
43 public class SetUtil {
44
45 public static <E> Set<E> fromArray(E[] array) {
46 if ((array == null) || (array.length == 0)) {
47 return new HashSet<E>();
48 }
49
50 Set<E> set = new HashSet<E>(array.length);
51
52 for (int i = 0; i < array.length; i++) {
53 set.add(array[i]);
54 }
55
56 return set;
57 }
58
59 public static Set<Long> fromArray(long[] array) {
60 if ((array == null) || (array.length == 0)) {
61 return new HashSet<Long>();
62 }
63
64 Set<Long> set = new HashSet<Long>(array.length);
65
66 for (int i = 0; i < array.length; i++) {
67 set.add(array[i]);
68 }
69
70 return set;
71 }
72
73 @SuppressWarnings("unchecked")
74 public static <E> Set<E> fromCollection(Collection<E> c) {
75 if ((c != null) && (Set.class.isAssignableFrom(c.getClass()))) {
76 return (Set)c;
77 }
78
79 if ((c == null) || (c.size() == 0)) {
80 return new HashSet<E>();
81 }
82
83 return new HashSet<E>(c);
84 }
85
86 public static <E> Set<E> fromEnumeration(Enumeration<E> enu) {
87 Set<E> set = new HashSet<E>();
88
89 while (enu.hasMoreElements()) {
90 set.add(enu.nextElement());
91 }
92
93 return set;
94 }
95
96 public static Set<String> fromFile(File file) throws IOException {
97 Set<String> set = new HashSet<String>();
98
99 UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
100 new FileReader(file));
101
102 String s = StringPool.BLANK;
103
104 while ((s = unsyncBufferedReader.readLine()) != null) {
105 set.add(s);
106 }
107
108 unsyncBufferedReader.close();
109
110 return set;
111 }
112
113 public static Set<String> fromFile(String fileName) throws IOException {
114 return fromFile(new File(fileName));
115 }
116
117 public static <E> Set<E> fromIterator(Iterator<E> itr) {
118 Set<E> set = new HashSet<E>();
119
120 while (itr.hasNext()) {
121 set.add(itr.next());
122 }
123
124 return set;
125 }
126
127 public static <E> Set<E> fromList(List<E> array) {
128 if ((array == null) || (array.size() == 0)) {
129 return new HashSet<E>();
130 }
131
132 return new HashSet<E>(array);
133 }
134
135 public static Set<String> fromString(String s) {
136 return fromArray(StringUtil.split(s, StringPool.NEW_LINE));
137 }
138
139 }