Syntactic Sugar
You know what I hate? I hate that I always am writing code, usually for tests, that looks like:
List<String> stuff = new ArrayList<String>(); stuff.add("fish"); stuff.add("cow"); stuff.add("dog");
So now I just type:
List<String> stuff = Om.list("fish","cow","dog");
Nothing exotic, but here’s the handy method that allows it, and several others of a related ilk. I particularly like the Om.map() method. Enjoy. I’ll share a few more soon.
package com.omino.roundabout; /** * Generic and System utility methods, like printf. * @author poly */ public class Om { ... /** * Syntactic utility for inlining object lists without the tedium of creating a list and adding to it. * @param <T> the implicit type of all the pieces * @param pieces things to put into the list * @return a mutable list. Add more to it or delete some if you like. */ public static <T> List<T> list(T...pieces) { List<T> result = new ArrayList<T>(); result.addAll(Arrays.asList(pieces)); return result; } /** * Syntactic utility for inlining a map. The map signature is sussed from * the first two items, but you can include as many pairs as you like. * @param <K> * @param <V> * @param key1 * @param value1 * @param theRestOfTheKeyValuePairs * @return a mutable map. */ @SuppressWarnings("unchecked") public static <K,V> Map<K,V> map(K key1,V value1,Object...theRestOfTheKeyValuePairs) { Map<K,V> result = new HashMap<K, V>(); result.put(key1,value1); for(int i = 0; i < theRestOfTheKeyValuePairs.length - 1; i += 2) { K key = (K)theRestOfTheKeyValuePairs[i]; V value = (V)theRestOfTheKeyValuePairs[i + 1]; result.put(key,value); } return result; } /** * Syntactic helper to make a set of objects. * @param <T> * @param items * @return */ public static <T> Set<T> set(T...items) { List<T> list = Om.list(items); Set<T> result = new HashSet<T>(list); return result; } ... }