Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
9
Help us understand the problem. What is going on with this article?
@shrhdk

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

More than 5 years have passed since last update.

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);
    }
}
9
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
shrhdk

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
9
Help us understand the problem. What is going on with this article?