LoginSignup
10

More than 5 years have passed since last update.

JavaでList, Set, Mapをリテラルっぽく記述するヘルパーメソッド

Last updated at Posted at 2014-07-06

JavaでList, Set, Mapを簡単に生成するヘルパーメソッドです。
コードはパブリックドメインです。

sample
import java.util.*;
import static org.example.CollectionsHelper.*;

List<String> list = $("foo", "bar", "foobar");
Set<String> set = $s("foo", "bar", "foobar");
Map<String, Integer> map = $m(_("foo", 1), _("bar", 2), _("foobar", 3));
CollectionsHelper.java
package org.example;

import java.util.*;

public class CollectionsHelper {
    private CollectionsHelper() {
        throw new AssertionError();
    }

    public static <T> List<T> $(T... values) {
        final List<T> list = new ArrayList<T>(values.length);
        for (T value : values) {
            list.add(value);
        }
        return list;
    }

    public static <T> Set<T> $s(T... values) {
        final Set<T> set = new HashSet<T>(values.length);
        for (T value : values) {
            set.add(value);
        }
        return set;
    }

    public static <K, V> Map<K, V> $m(Map.Entry<? extends K, ? extends V>... entries) {
        final Map<K, V> map = new HashMap<K, V>();
        for (Map.Entry<? extends K, ? extends V> entry : entries) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    public static <K, V> Map.Entry<K, V> _(K key, V value) {
        return new AbstractMap.SimpleEntry<K, V>(key, value);
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10