Initialization of an ArrayList in one line

后端 未结 30 2205
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
相关标签:
30条回答
  • 2020-11-22 01:43

    With Guava you can write:

    ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");
    

    In Guava there are also other useful static constructors. You can read about them here.

    0 讨论(0)
  • 2020-11-22 01:43

    You can use the below statements:

    Code Snippet:

    String [] arr = {"Sharlock", "Homes", "Watson"};
    
    List<String> names = Arrays.asList(arr);
    
    0 讨论(0)
  • 2020-11-22 01:44

    Try with this code line:

    Collections.singletonList(provider)
    
    0 讨论(0)
  • 2020-11-22 01:44

    interestingly no one-liner with the other overloaded Stream::collect method is listed

    ArrayList<String> places = Stream.of( "Buenos Aires", "Córdoba", "La Plata" ).collect( ArrayList::new, ArrayList::add, ArrayList::addAll );
    
    0 讨论(0)
  • 2020-11-22 01:45

    If you need a simple list of size 1:

    List<String> strings = new ArrayList<String>(Collections.singletonList("A"));
    

    If you need a list of several objects:

    List<String> strings = new ArrayList<String>();
    Collections.addAll(strings,"A","B","C","D");
    
    0 讨论(0)
  • 2020-11-22 01:46

    Simply use below code as follows.

    List<String> list = new ArrayList<String>() {{
                add("A");
                add("B");
                add("C");
    }};
    
    0 讨论(0)
提交回复
热议问题