Initialization of an ArrayList in one line
Asked Answered
M

35

3346

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

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then, I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?

Meaningful answered 17/6, 2009 at 4:10 Comment(9)
If this is intended for unit testing, try groovy out for a swing. You can write your test code in it while testing java code, and use ArrasyList<String> places = ["Buenos Aires", "Córdoba", "La Plata"]Errantry
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>): Map<String, List<String>> myMap = new HashMap<>();Dipper
See also https://mcmap.net/q/36091/-create-arraylist-from-arrayAliber
use double bracing initialization :)Guevara
It seems like you answered yourself in the question: ArrayList<String> places = new ArrayList<String>(asList("Buenos Aires", "Córdoba", "La Plata")); Arrays in Arrays.asList is not needed.Overprint
Stream.of("val1", "val2").collect(Collectors.toList()); //creates ArrayList, Java8 solution.Jake
Why not just use String [] places = {"Buenos Aires", "Córdoba", "La Plata"); ?Infect
@PaulSmith He might be interested in an elastic array that can grow dynamically. Your initialization will make places to have just three elements.Greenstone
I don't understand why we cannot have some thing like List<Integer> = {1, 2, 3, 4, 5} in Java. Create and init a mutable array in one line, as I know Python and Swift could do that.Hylomorphism
Y
2232

Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

The catch is that there is quite a bit of typing required to refer to that list instance.

There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):

ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):

List<String> list = ["A", "B", "C"];

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.

Yabber answered 17/6, 2009 at 4:13 Comment(3)
See stackoverflow.com/questions/924285 for more information about the double-brace initialization, pros and cons.Sharyl
you don't need the second <String>.Clap
@Clap The "diamond operator" was introduced in Java 7, which wasn't released when I wrote this answer back in 2009 ;)Yabber
S
2715

It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

Or if you have only one element:

List<String> places = Collections.singletonList("Buenos Aires");

This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:

ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

And import the correct package:

import java.util.Arrays;
Satisfy answered 17/6, 2009 at 4:15 Comment(9)
Yes, my class has an private ArrayList<String>.Meaningful
@Marcase: Can you not change your class to use a List instead of ArrayList?Smoking
@Software Monkey: I wanted to know how to initialize an ArrayList. It's not real code, I was just testing things out. So, yes I might change it to List, but that would not answer my question.Meaningful
As per my answer, if you're not using methods specific to ArrayList, it would be better design to change the declaration to List. Specify interfaces, not implementations.Aliber
@Christoffer Hammarström: if he changes the declaration to List and uses the List<String> places = Arrays.asList(...); he will not be able to use places.add("blabla")Karyotin
@maks: True, except that's because of using asList(...), not because of changing the declaration from ArrayList to List. I would put it as "he will not need to use places.add("blabla")". He already changed it to asList(...) himself.Aliber
Just to be clear, asList(...) returns a fixed size List that blows up on mutating operations like remove and clear, things the List contract claims to support. Even if you left declaration as List, you sill need to use List l = new ArrayList(asList(...)) in order to get an object that doesn't throw OperationNotSupported exceptions. Liskov Substitution Principle anyone?Dreamadreamer
I find this answer slightly misleading, because it suggests that Arrays.asList returns something immutable. That's not true. It returns a list that can't be lengthened or shortened; but which can be mutated by swapping out an element for a new value.Sr
How can it be that I need to lookup how to initialise a fucking mutable array every time I need to? And this is supposedly the best way? What an horrible language.Spondee
Y
2232

Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

The catch is that there is quite a bit of typing required to refer to that list instance.

There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):

ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):

List<String> list = ["A", "B", "C"];

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.

Yabber answered 17/6, 2009 at 4:13 Comment(3)
See stackoverflow.com/questions/924285 for more information about the double-brace initialization, pros and cons.Sharyl
you don't need the second <String>.Clap
@Clap The "diamond operator" was introduced in Java 7, which wasn't released when I wrote this answer back in 2009 ;)Yabber
D
1134

The simple answer

Java 9 or later:

List<String> strings = List.of("foo", "bar", "baz");

List.of(...) will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.

This does not allow null elements.

Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");

Arrays.asList(...) will give you a List* backed by an array, so it cannot change length.
But you can call List.set(...), so it's still mutable.

This does allow null elements.

* Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList,
which is a different class from java.util.ArrayList, even though their simple names are the same.

Static import

You can make Java 8 Arrays.asList even shorter with a static import:

import static java.util.Arrays.asList;  
...
List<String> strings = asList("foo", "bar", "baz");

Any modern IDE* will suggest and do this for you.

I don't recommend statically importing the List.of method as just of, because it's confusing.

* For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...

Using Streams

Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:

Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:

import static java.util.stream.Collectors.toList;
...
var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8

But preferably, just use the Stream without collecting it to a List.

If you specifically need a java.util.ArrayList*

If you want to both prepopulate an ArrayList and add to it afterwards, use

List<String> strings = new ArrayList<>(List.of("foo", "bar"));

or in Java 8 or earlier:

List<String> strings = new ArrayList<>(asList("foo", "bar"));

or using Stream:

import static java.util.stream.Collectors.toCollection;

List<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));

Then you can add to it after construction:

strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.

*You probably don't need specifically an ArrayList. To quote JEP 269:

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.

(emphasis mine)

Program to interfaces, not to implementations

You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.

Which you are most likely not doing.

Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).

Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.

For example, if you're passing an ArrayList to a void method(...):

// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) { 
    for (String s : strings) { ... } 
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need random access, .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.

Denison answered 9/9, 2010 at 12:33 Comment(6)
It's worth mentioning that streams need to be closed whereas lists do not.Dyche
@MikeLowery: Are you thinking of InputStream and OutputStream? java.util.stream.Stream does not need to be closed. It does need a terminal operation, but you're not going to forget that, because without it the stream does nothing.Aliber
That's what I was actually working with, yes. But java.util.stream.Stream extends BaseStream which does have a close() method because it implements AutoCloseable. At the very least an IDE is going to complain about a potential resource leak.Dyche
@MikeLowery: You don't need to close Streams in general, and i haven't seen IntelliJ IDEA complain about me not doing so. See #22125669Aliber
Eclipse does, provided you have it configured to find potential resource leaks. Personally I think it's confusing to have a class implement AutoCloseable when it may not need to actually be closed, but that's exactly what they did (see API note).Dyche
Also Arrays.asList allows passing null elements, while List.of doesn't.Manhandle
I
122

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");
Incommunicative answered 30/8, 2011 at 4:33 Comment(0)
R
68

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.

Revengeful answered 29/7, 2013 at 13:24 Comment(4)
I'm pretty sure you can do this with just java.util.Arrays such as, List<String> names = Arrays.asList("Beckah", "Sam", "Michael");Lengthy
@Lengthy method Arrays.asLists creates object of type List, while question is about creating ArrayListMosa
This method is not actually very useful and will likely be deprecated in the future.Cooler
@Lengthy Arrays.asList creates a list that can't be modified. If the list needs to be modified Lists.newArrayList will work and Arrays.asList won't.Aleece
N
48

With and above, as suggested in JEP 269: Convenience Factory Methods for Collections, creating an unmodifiable List instead of an ArrayList could be achieved using collection literals now with -

List<String> list = List.of("A", "B", "C");

Set<String> set = Set.of("A", "B", "C");

A similar approach would apply to Map as well -

Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

which is similar to Collection Literals proposal as stated by @coobird. Further clarified in the JEP as well -


Alternatives

Language changes have been considered several times, and rejected:

Project Coin Proposal, 29 March 2009

Project Coin Proposal, 30 March 2009

JEP 186 discussion on lambda-dev, January-March 2014

The language proposals were set aside in preference to a library-based proposal as summarized in this message.

Related: What is the point of overloaded Convenience Factory Methods for Collections in Java 9

Necrolatry answered 2/2, 2017 at 17:36 Comment(2)
Note that this creates an immutable List and not a modifiable ArrayList!Adamek
@Adamek precisely an unmodifiable one, if one was to mentionNecrolatry
C
36

Collection literals didn't make it into Java 8, but it is possible to use the Stream API to initialize a list in one rather long line:

List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());

If you need to ensure that your List is an ArrayList:

ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));
Centralize answered 3/4, 2014 at 23:21 Comment(0)
M
34
import com.google.common.collect.ImmutableList;

....

List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
Munguia answered 12/5, 2010 at 13:14 Comment(7)
I don't want to add a new dependency just to do that.Meaningful
That's the same as Collections.unmodifiableList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata")), which becomes unmodifiableList(asList("Buenos Aires", "Córdoba", "La Plata")) with static imports. You don't need Google Collections for this.Aliber
No, it's not the same. As ImmutableList is documenting its immutability in the result type when unmodifiableList masquerades it as a normal List.Unni
Instead of the immutable one, google collections also offer mutable array list: List<String> = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");Bartholomew
You're going to pass that ImmutableList to other methods that take a List, and then you've lost that documentation anyway.Aliber
@ChristofferHammarström No, you can still check its type at runtime, which can be useful.Adamek
@xuiqzy: Yes, but i was talking about in source code. Running extra code to check what type of List is being passed isn't what i call documentation. And if you're doing that you can just check if its a Collections.UnmodifiableList so the original point is moot anyway.Aliber
R
26

You could create a factory method:

public static ArrayList<String> createArrayList(String ... elements) {
  ArrayList<String> list = new ArrayList<String>();
  for (String element : elements) {
    list.add(element);
  }
  return list;
}

....

ArrayList<String> places = createArrayList(
  "São Paulo", "Rio de Janeiro", "Brasília");

But it's not much better than your first refactoring.

For greater flexibility, it can be generic:

public static <T> ArrayList<T> createArrayList(T ... elements) {
  ArrayList<T> list = new ArrayList<T>();
  for (T element : elements) {
    list.add(element);
  }
  return list;
}
Reign answered 4/5, 2010 at 0:57 Comment(3)
Look back at the original post, it is asking for array initialization in one line, not 7 additional lines.Bartholomew
@LeoHolanda: Creating factory methods for every little thing is too much, I agree. But depending on the situation, and on the number of times that that method is going to be used, it might make sense to create it. Creating extra abstraction layers is meant to remove complexity, by creating more meaningful methods that capture the intent of the designer.Impacted
I think we can replace the enhanced for with Collections.addAll(elements) as described here.Brunei
E
14

In Java 9 we can easily initialize an ArrayList in a single line:

List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

or

List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

This new approach of Java 9 has many advantages over the previous ones:

  1. Space Efficiency
  2. Immutability
  3. Thread Safe

See this post for more details -> What is the difference between List.of and Arrays.asList?

Emelda answered 6/10, 2017 at 1:16 Comment(1)
The first example does not create an ArrayList, despite the preceding sentence indicating that it does.Oakum
A
13

Java 9 has the following method to create an immutable list as documented (or documented as unmodifiable Java 10+):

List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

which is easily adapted to create a mutable list, if required:

List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

Similar methods are available for Set and Map.

Please note that these methods do not accept null elements, a little bit hidden in the documentation:

Throws: NullPointerException - if an element is null ...

Amersham answered 6/12, 2016 at 9:57 Comment(1)
Its good that you explicitly said "immutable list" and then showed another example of mutable list because it makes it clear which to use when.Terreverte
C
10

Simply use below code as follows.

List<String> list = new ArrayList<String>() {{
            add("A");
            add("B");
            add("C");
}};
Collage answered 21/9, 2013 at 9:43 Comment(1)
This is not one-lineKerns
M
8

(Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList method is fixed size, but that's not the only issue with it. It also doesn't handle inheritance very well. For instance, suppose you have the following:

class A {}
class B extends A {}
    
public List<A> getAList() {
    return Arrays.asList(new B());
}

The above results in a compiler error, because List<B> (which is what is returned by Arrays.asList) is not a subclass of List<A>, even though you can add Objects of type B to a List<A> object. To get around this, you need to do something like:

new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))

This is probably the best way to go about doing this, especially if you need an unbounded list or need to use inheritance.

Mossman answered 6/6, 2013 at 5:44 Comment(1)
this is relevant only for Java versions previous to Java 8 (or even older) - the mentioned compiler error cannot be reproduced with Java 8 or later (example ideone.com/WHPY5d) - with not-so-old versions, the compiler is able to correctly infer the list typeAmersham
C
8

About the most compact way to do this is:

Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);
Camisado answered 15/12, 2014 at 11:44 Comment(0)
A
8

With Eclipse Collections you can write the following:

List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");

You can also be more specific about the types and whether they are Mutable or Immutable.

MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");

You can also do the same with Sets and Bags:

Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");

Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");

Note: I am a committer for Eclipse Collections.

Amaya answered 28/1, 2015 at 1:30 Comment(0)
S
8

Here is another way:

List<String> values = Stream.of("One", "Two").collect(Collectors.toList());
Surinam answered 28/2, 2017 at 22:50 Comment(0)
S
6

You can use the below statements:

Code Snippet:

String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);
Squinch answered 17/6, 2009 at 4:10 Comment(1)
You can inline first expression to have compact solution: letters = Arrays.asList(new String[]{"A", "B", "C"});Millur
S
6
List<String> names = Arrays.asList("2", "@2234", "21", "11");
Sailesh answered 22/6, 2014 at 8:12 Comment(1)
Note that this creates an immutable List and not a modifiable ArrayList!Adamek
R
6

There are multiple ways to create and initialize list in one line. Some examples:

//Using Double brace initialization, creates a new (anonymous) subclass of ArrayList
List<String> list1 = new ArrayList<>() {{ add("A");  add("B"); }};

//Immutable List
List<String> list2 = List.of("A", "B");

//Fixed size list. Can't add or remove element, though replacing the element is allowed.
List<String> list3 = Arrays.asList("A", "B");

//Modifiable list
List<String> list4 = new ArrayList<>(Arrays.asList("A", "B"));

//Using Java Stream, no guarantees on the type, mutability, serializability, or thread-safety
List<String> list5 = Stream.of("A", "B").collect(Collectors.toList());

//Thread safe List
List<String> list6 = new CopyOnWriteArrayList<>(Arrays.asList("A", "B"));
Remde answered 27/12, 2022 at 14:5 Comment(0)
E
5

Like Tom said:

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

But since you complained of wanting an ArrayList, you should first know that ArrayList is a subclass of List and you could simply add this line:

ArrayList<String> myPlaces = new ArrayList(places);

Although, that might make you complain about 'performance'.

In that case, it doesn't make sense to me, why, since your list is predefined it wasn't defined as an array (since the size is known at the time of initialization). And if that's an option for you:

String[] places = { "Buenos Aires", "Córdoba", "La Plata" };

In case you don't care about the minor performance differences then you can also copy an array to an ArrayList very simply:

ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));

Okay, but in the future, you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list that will never change during run-time, then it's fitting to use an enum set, which would require re-compilation if the list needed to be changed in the future.

enum Places { BUENOS_AIRES, CORDOBA, LA_PLATA }

would become:

enum Places {
    BUENOS_AIRES("Buenos Aires", 123),
    CORDOBA("Córdoba", 456),
    LA_PLATA("La Plata", 789);

    String name;
    int code;

    Places(String name, int code) {
      this.name = name;
      this.code = code;
    }
}

Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared, e.g.:

for (Places p : Places.values()) {
    System.out.printf("The place %s has code %d%n",
                  p.name, p.code);
}

In that case, I guess you wouldn't need your ArrayList.

P.S. Randyaa demonstrated another nice way using the static utility method Collections.addAll.

Emlynn answered 17/6, 2013 at 17:57 Comment(0)
E
4

Yes. With the help of Arrays you can initialize an immutable List (instead of an ArrayList) in one line:

List<String> strlist = Arrays.asList("aaa", "bbb", "ccc");
Exist answered 13/9, 2016 at 5:54 Comment(0)
H
4

You can use StickyList from Cactoos:

List<String> names = new StickyList<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Hair answered 25/6, 2017 at 17:48 Comment(0)
B
4

Using Arrays.asList("Buenos Aires", "Córdoba", "La Plata"); is correct. but Any calls to Arrays.asList() with zero arguments or only one argument could be replaced with either a call to Collections.singletonList() or Collections.emptyList() which will save some memory.

Note: the list returned by Collections.singletonList() is immutable, while the list returned Arrays.asList() allows calling the set() method. This may break the code in rare cases.

Brainstorming answered 19/5, 2021 at 11:35 Comment(0)
W
3

Try with this code line:

Collections.singletonList(provider)
Wick answered 16/5, 2016 at 13:45 Comment(1)
Add a brief description of your answer.Jade
S
2

In Java, you can't do

ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

As was pointed out, you'd need to do a double brace initialization:

List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};

But this may force you into adding an annotation @SuppressWarnings("serial") or generate a serial UUID which is annoying. Also most code formatters will unwrap that into multiple statements/lines.

Alternatively you can do

List<String> places = Arrays.asList(new String[] {"x", "y" });

but then you may want to do a @SuppressWarnings("unchecked").

Also according to javadoc you should be able to do this:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

But I'm not able to get it to compile with JDK 1.6.

Stricklan answered 13/2, 2012 at 21:47 Comment(1)
Wrong! You can do the first line, and that is the right answer btwLeucippus
L
1
Collections.singletonList(messageBody)

If you'd need to have a list of one item!

Collections is from java.util package.

Lath answered 3/4, 2015 at 9:30 Comment(0)
M
1

The best way to do it:

package main_package;

import java.util.ArrayList;


public class Stackkkk {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<Object>();
        add(list, "1", "2", "3", "4", "5", "6");
        System.out.println("I added " + list.size() + " element in one line");
    }

    public static void add(ArrayList<Object> list, Object... objects) {
        for (Object object : objects)
            list.add(object);
    }
}

Just create a function that can have as many elements as you want and call it to add them in one line.

Mindimindless answered 17/7, 2016 at 18:31 Comment(1)
If you go through all the trouble you might as well make it a template method instead of using plain Object.Snipe
P
1

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 );
Pope answered 4/10, 2019 at 15:4 Comment(1)
Totally different answer. ThanksXerophagy
S
0

For me, Arrays.asList() is the best and most convenient one. I always like to initialize that way. If you are a beginner in Java Collections then I would like you to refer ArrayList initialization.

Sarto answered 7/12, 2014 at 5:37 Comment(1)
Why is Arrays.asList() better than creating a new ArrayList in one line with add() methods?Fang
D
0

Here is code by abacus-common

// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// The most efficient way, which is similar with Arrays.asList(...) in JDK. 
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");

Declaration: I'm the developer of abacus-common.

Dresden answered 28/11, 2016 at 19:56 Comment(0)
U
0

Why not make a simple utility function that does this?

static <A> ArrayList<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}

"ll" stands for "literal list".

ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
Uticas answered 4/12, 2017 at 11:23 Comment(1)
you could use Collections.addAll instead of the for loop. Also, if you name the method list, the name requires no explanation :)Vibraculum
C
0

Simplest way : you can use this approach to add multiple elements to any type of collection like ArrayList and HashSet

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");
Chiropodist answered 13/2, 2022 at 5:55 Comment(0)
M
0

I suspect the original question relates to a desire to declare and initialize the ArrayList in one line and avoid having to create separate code to acheive the initialization. Thus, the answer lies in the question but may be generalized as follows:

ArrayList&lt;AnyClass> arrayListOfAnyClass = new ArrayList<>(Arrays.asList(
  new AnyClass(param11, param12, ...),
  new AnyClass(param21, param22, ...),
  new AnyClass(param31, param32, ...),
  ...
));
Maitund answered 20/11, 2023 at 14:32 Comment(0)
A
-1

Actually, it's possible to do it in one line:

Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})
Aldin answered 2/6, 2013 at 13:34 Comment(2)
May I ask what this adds to the question? This answer is already covered multiple times by other answers.Revolving
This is actually a really bad soluition as it creates an ABSTRACT LIST. You will not be able to add anything more to the container.Roop
H
-5
public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

This is the implementation of Arrays.asList, so you could go with

ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");
Helgeson answered 31/7, 2012 at 13:22 Comment(1)
-1 Those are not the same class.Seineetmarne

© 2022 - 2024 — McMap. All rights reserved.