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

More than 1 year has passed since last update.

JavaでList, Set, Mapを簡単に生成するヘルパーメソッドです。

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));
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) {
        return list;

    public static <T> Set<T> $s(T... values) {
        final Set<T> set = new HashSet<T>(values.length);
        for (T value : values) {
        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);
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.