4
Mar
2011

A DSL for collections in Java

When writing Java code I often find it laborious to create collections using the java.util.* collection classes. To avoid this, I’ve been using a mini-DSL to reduce my collections code.

import static com.joejag.common.collections.Dsl.*;

// A list
List list = list("abc", "def");
      
// A set
Set set = set("Sleepy", "Sneezy", "Dozy");
      
// A Map
Map map = map(entry("Joe", 28), entry("Gerry", 39));

Here is the underlying code.

package com.joejag.common.collections;


import java.util.*;

public class Dsl {
    public static <T> List<T> list(T... args) {
        return Arrays.asList(args);
    }

    public static <T> Set<T> set(T... args) {
        Set<T> result = new HashSet<T>(args.length);
        result.addAll(Arrays.asList(args));
        return result;
    }

    public static <K, V> Map<K, V> map(Entry<? extends K, ? extends V>... entries) {
        Map<K, V> result = new HashMap<K, V>(entries.length);

        for (Entry<? extends K, ? extends V> entry : entries)
            if (entry.value != null)
                result.put(entry.key, entry.value);

        return result;
    }

    public static <K, V> Entry<K, V> entry(K key, V value) {
        return new Entry<K, V>(key, value);
    }

    public static class Entry<K, V> {
        K key;
        V value;

        public Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    public static void main(String args[]) {
        List<String> list = list("abc", "def");
        System.out.println(list);

        Set<String> set = set("Sleepy", "Sneezy", "Dozy");
        System.out.println(set);

        Map<String, Integer> map = map(entry("Joe", 28), entry("Gerry", 39));
        System.out.println(map);
    }
}

I’ve noticed that the Google Collections project has morphed into Guava which has great reusable code for collections and a lot of other common Java tasks.

{3} Comments

Sam Barker | 6 Mar, 2011

You seem to have lost something in posting this up, as it doesn’t compile ;) The reason I checked is I’m suspicious of your generics.

// Sam included a version that compiles here

I’ve also simplified your implementation of list.

Joe Wright | 6 Mar, 2011

@Sam

Cheers for that, I forgot to escape the code. You can see the lovely generics on display now.

I’ve updated the post to use the simpler list implementation you suggested. Thanks very much!

Lukasz | 18 May, 2011

“When writing Java code I often find it laborious to create collections using the java.util.* collection classes.”

This is exactly why you should switch to Scala :D

Post your comment