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