builder for HashMap

前端 未结 15 2153
迷失自我
迷失自我 2020-11-30 00:17

Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashM         


        
相关标签:
15条回答
  • 2020-11-30 01:00

    Not quite a builder, but using an initializer:

    Map<String, String> map = new HashMap<String, String>() {{
        put("a", "1");
        put("b", "2");
    }};
    
    0 讨论(0)
  • 2020-11-30 01:00

    Here is a very simple one ...

    public class FluentHashMap<K, V> extends java.util.HashMap<K, V> {
      public FluentHashMap<K, V> with(K key, V value) {
        put(key, value);
        return this;
      }
    
      public static <K, V> FluentHashMap<K, V> map(K key, V value) {
        return new FluentHashMap<K, V>().with(key, value);
      }
    }
    

    then

    import static FluentHashMap.map;
    
    HashMap<String, Integer> m = map("a", 1).with("b", 2);
    

    See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065

    0 讨论(0)
  • 2020-11-30 01:01

    Underscore-java can build hashmap.

    Map<String, Object> value = U.objectBuilder()
            .add("firstName", "John")
            .add("lastName", "Smith")
            .add("age", 25)
            .add("address", U.arrayBuilder()
                .add(U.objectBuilder()
                    .add("streetAddress", "21 2nd Street")
                    .add("city", "New York")
                    .add("state", "NY")
                    .add("postalCode", "10021")))
            .add("phoneNumber", U.arrayBuilder()
                .add(U.objectBuilder()
                    .add("type", "home")
                    .add("number", "212 555-1234"))
                .add(U.objectBuilder()
                    .add("type", "fax")
                    .add("number", "646 555-4567")))
            .build();
        // {firstName=John, lastName=Smith, age=25, address=[{streetAddress=21 2nd Street,
        // city=New York, state=NY, postalCode=10021}], phoneNumber=[{type=home, number=212 555-1234},
        // {type=fax, number=646 555-4567}]}
    
    0 讨论(0)
提交回复
热议问题