Last active
December 27, 2015 01:29
-
-
Save vegaasen/7245781 to your computer and use it in GitHub Desktop.
SetUtils, simple utils in order to convert to sorted sets, and sets from list and array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Array; | |
import java.util.*; | |
/** | |
* @author <a href="mailto:vegaasen@gmail.com">Vegard Aasen</a> | |
* @since 3:13 PM | |
*/ | |
public final class SetUtils { | |
private static final String EMPTY = ""; | |
private SetUtils() { | |
} | |
public static <T> Set<T> toSet(final T[] arr) { | |
return toSet(Arrays.asList(arr)); | |
} | |
public static <T> Set<T> toSet(final List<T> list) { | |
if (list == null || list.isEmpty()) { | |
return Collections.emptySet(); | |
} | |
Set<T> set = new HashSet<>(); | |
set.addAll(list); | |
return set; | |
} | |
@SuppressWarnings("unchecked") | |
public static <T> T[] toSortedSet(final Set<T> set, final Class<?> type) { | |
return toSortedSet(set, type, new Comparator<T>() { | |
@Override | |
public int compare(final T s0, final T s1) { | |
return s0.toString().compareToIgnoreCase(s1.toString()); | |
} | |
}); | |
} | |
@SuppressWarnings("unchecked") | |
public static <T> T[] toSortedSet(final Set<T> set, final Class<?> type, Comparator<T> comparator) { | |
if (set == null || set.isEmpty()) { | |
return (T[]) Array.newInstance(type, 0); | |
} | |
final T[] array = set.toArray((T[]) Array.newInstance(type, set.size())); | |
Arrays.sort(array, comparator); | |
return array; | |
} | |
public static String getAsSeparatedList(Set<?> obs) { | |
if (obs == null) { | |
return EMPTY; | |
} | |
StringBuilder bb = new StringBuilder(); | |
int c = 0; | |
for (Object o : obs) { | |
if (o != null) { | |
bb.append(o.toString()); | |
if (c != obs.size()) { | |
bb.append(","); | |
} | |
c++; | |
} | |
} | |
return bb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment