Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make passing a list with just one value to an other method less verbose

Tags:

java

arraylist

If I have a method like this

private void setStringList(List<String> aList) { ... }

Then this is obviously possible

private void testOnly() {
    List<String> myDummyList = new ArrayList<String>();
    myDummyList.add("someValue");
    setStringList(myDummyList);
}

but is there a way to make it less verbose like this

private void testOnly2() {        
    setStringList(new ArrayList<String>().add("someValue"));
}

I know above is compilation error but just showing to demonstrate what I want to achieve just to make it less verbose.

like image 526
Java Ka Baby Avatar asked Dec 13 '22 09:12

Java Ka Baby


1 Answers

Yes:

private void testOnly2() {        
    setStringList(new ArrayList<String>(Arrays.asList("someValue")));
}

or, depending on what you use the argument for in setStringList:

private void testOnly2() {        
    setStringList(Arrays.asList("someValue"));
}

Another option is to use an instance-initializer, like this:

private void testOnly2() {
    setStringList(new ArrayList<String>() {{
        add("someValue");
    }});
}

(this creates an anonymous subclass of ArrayList though.)

like image 187
aioobe Avatar answered Dec 21 '22 22:12

aioobe