Java ArrayList and HashMap on-the-fly

后端 未结 7 1128
甜味超标
甜味超标 2021-01-31 07:07

Can someone please provide an example of creating a Java ArrayList and HashMap on the fly? So instead of doing an add() or put()

相关标签:
7条回答
  • 2021-01-31 07:48

    You mean like this?

    public List<String> buildList(String first, String second)
    {
         List<String> ret = new ArrayList<String>();
         ret.add(first);
         ret.add(second);
         return ret;
    }
    
    ...
    
    List<String> names = buildList("Jon", "Marc");
    

    Or are you interested in the ArrayList constructor which takes a Collection<? extends E>? For example:

    String[] items = new String[] { "First", "Second", "Third" };
    // Here's one way of creating a List...
    Collection<String> itemCollection = Arrays.asList(items);
    // And here's another
    ArrayList<String> itemList = new ArrayList<String>(itemCollection);
    
    0 讨论(0)
  • 2021-01-31 07:50
    List<String> list = new ArrayList<String>() {
     {
        add("value1");
        add("value2");
     }
    };
    
    Map<String,String> map = new HashMap<String,String>() {
     {
        put("key1", "value1");
        put("key2", "value2");
     }
    };
    
    0 讨论(0)
  • 2021-01-31 07:54

    Arrays can be converted to Lists:

    List<String> al = Arrays.asList("vote", "for", "me"); //pandering
    

    Note that this does not return an ArrayList but an arbitrary List instance (in this case it’s an Array.ArrayList)!

    Bruno's approach works best and could be considered on the fly for maps. I prefer the other method for lists though (seen above):

    Map<String,String> map = new HashMap<String,String>() {
     {
        put("key1", "value1");
        put("key2", "value2");
     }
    };
    
    0 讨论(0)
  • 2021-01-31 07:54

    for short lists:

        List<String> ab = Arrays.asList("a","b");
    
    0 讨论(0)
  • 2021-01-31 07:56

    A nice way of doing this is using Google Collections:

    List<String> list = ImmutableList.of("A", "B", "C");
    
    Map<Integer, String> map = ImmutableMap.of(
      1, "A",
      2, "B",
      3, "C");
    
    0 讨论(0)
  • 2021-01-31 07:56

    Use a nice anonymous initializer:

    List<String> list = new ArrayList<String>() {{
        add("a");
        add("b");
    }};
    

    Same goes for a Map:

    Map<String, String> map = new HashMap<String, String>() {{
        put("a", "a");
        put("b", "b");
    }};
    

    I find this the most elegant and readable.

    Other methods demand creating an array first, then converting it to a List - too expensive in my taste, and less readable.

    0 讨论(0)
提交回复
热议问题