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