001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
018
019 import java.io.File;
020 import java.io.FileReader;
021 import java.io.IOException;
022
023 import java.util.Collection;
024 import java.util.Enumeration;
025 import java.util.HashSet;
026 import java.util.Iterator;
027 import java.util.List;
028 import java.util.Set;
029
030
033 public class SetUtil {
034
035 public static <E> Set<E> fromArray(E[] array) {
036 if ((array == null) || (array.length == 0)) {
037 return new HashSet<E>();
038 }
039
040 Set<E> set = new HashSet<E>(array.length);
041
042 for (int i = 0; i < array.length; i++) {
043 set.add(array[i]);
044 }
045
046 return set;
047 }
048
049 public static Set<Long> fromArray(long[] array) {
050 if ((array == null) || (array.length == 0)) {
051 return new HashSet<Long>();
052 }
053
054 Set<Long> set = new HashSet<Long>(array.length);
055
056 for (int i = 0; i < array.length; i++) {
057 set.add(array[i]);
058 }
059
060 return set;
061 }
062
063 @SuppressWarnings("rawtypes")
064 public static <E> Set<E> fromCollection(Collection<E> c) {
065 if ((c != null) && (Set.class.isAssignableFrom(c.getClass()))) {
066 return (Set)c;
067 }
068
069 if ((c == null) || (c.size() == 0)) {
070 return new HashSet<E>();
071 }
072
073 return new HashSet<E>(c);
074 }
075
076 public static <E> Set<E> fromEnumeration(Enumeration<E> enu) {
077 Set<E> set = new HashSet<E>();
078
079 while (enu.hasMoreElements()) {
080 set.add(enu.nextElement());
081 }
082
083 return set;
084 }
085
086 public static Set<String> fromFile(File file) throws IOException {
087 Set<String> set = new HashSet<String>();
088
089 UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
090 new FileReader(file));
091
092 String s = StringPool.BLANK;
093
094 while ((s = unsyncBufferedReader.readLine()) != null) {
095 set.add(s);
096 }
097
098 unsyncBufferedReader.close();
099
100 return set;
101 }
102
103 public static Set<String> fromFile(String fileName) throws IOException {
104 return fromFile(new File(fileName));
105 }
106
107 public static <E> Set<E> fromIterator(Iterator<E> itr) {
108 Set<E> set = new HashSet<E>();
109
110 while (itr.hasNext()) {
111 set.add(itr.next());
112 }
113
114 return set;
115 }
116
117 public static <E> Set<E> fromList(List<E> array) {
118 if ((array == null) || (array.size() == 0)) {
119 return new HashSet<E>();
120 }
121
122 return new HashSet<E>(array);
123 }
124
125 public static Set<String> fromString(String s) {
126 return fromArray(StringUtil.split(s, StringPool.NEW_LINE));
127 }
128
129 }