Thursday, March 26, 2009

CollectionUtils

The better way to define collections:



public class CollectionUtils {

public static <T> T[] ar(T... ts) {
return ts;
}

public static <T> Set<T> set(T... ts) {
return new HashSet<T>(Arrays.asList(ts));
}

public static<K,V> Map<K, V> map(K[] keys, V[] values) {
Map<K,V> result = new HashMap<K,V>();
int i = 0;
for ( K key : keys ){
if ( values.length > i ){
result.put( key, values[i++] );
} else {
result.put (key, null);
}
}
return result;
}

}


It's easier to initialize collections. Exmaple

Map<String, Object> debugObjects =
map(ar ( "statistics", "usersCache", "templateConfig", "throttler" ),
ar ( statistics , usersCache , templateConfig , throttler )
);


Borrowed from here

No comments:

Post a Comment