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