How to Initialize List<String> Object in Java

How to initialize ListString object in Java?

If you check the API for List you'll notice it says:

Interface List<E>

Being an interface means it cannot be instantiated (no new List() is possible).

If you check that link, you'll find some classes that implement List:

All Known Implementing Classes:

AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector

Some of those can be instantiated (the ones that are not defined as abstract class). Use their links to know more about them, I.E: to know which fits better your needs.

The 3 most commonly used ones probably are:

 List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();

Bonus:

You can also instantiate it with values, in an easier way, using the Arrays class, as follows:

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));

But note you are not allowed to add more elements to that list, as it's fixed-size.

How to make a new List in Java

List myList = new ArrayList();

or with generics (Java 7 or later)

List<MyType> myList = new ArrayList<>();

or with generics (Old java versions)

List<MyType> myList = new ArrayList<MyType>();

How to Create and Initialize (in Java) a ListString[] in the same statement? (Editors please NOTE: this *not* the same as just a ListString)

The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.

to create a mutable list

final List<String[]> rolesCsv =
new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));

Otherwise (despite the array, its element, will not be immutable)

final List<String[]> rolesCsv =
Collections.singletonList(new String[]{"Role Name","Description"})

What is the shortest way to initialize List of strings in java?

There are various options. Personally I like using Guava:

List<String> strings = Lists.newArrayList("s1", "s2", "s3");

(Guava's a library worth having anyway, of course :)

Using just the JDK, you could use:

List<String> strings = Arrays.asList("s1", "s2", "s3");

Note that this will return an ArrayList, but that's not the normal java.util.ArrayList - it's an internal one which is mutable but fixed-size.

Personally I prefer the Guava version as it makes it clear what's going on (the list implementation which will be returned). It's also still clear what's going on if you statically import the method:

// import static com.google.common.collect.Lists.newArrayList;
List<String> strings = newArrayList("s1", "s2", "s3");

... whereas if you statically import asList it looks a little odder.

Another Guava option, if you don't want a modifiable-in-any-way list:

ImmutableList<String> strings = ImmutableList.of("s1", "s2", "s3");

I typically want to either have a completely mutable list (in which case Lists.newArrayList is best) or a completely immutable list (in which case ImmutableList.of is best). It's rare that I really want a mutable-but-fixed-size list.

MapString, ListString, Object add new list entry when key exists

So, let's assume there is a map of some ids to objects of type ObjectOne: Map<ID, ObjectOne>.

The key IDs are converted to some Code type by a database call, and the ObjectOne values of the first map are just collected into another map using Collectors.groupingBy and Collectors.mapping as intended initially:

Map<ID, ObjectOne> initialMap = ...;

Map<Code, List<ObjectOne>> mapByCode = initialMap
.entrySet()
.stream() // Stream<Map.Entry<ID, ObjectOne>>
.collect(Collectors.groupingBy(
e -> repository.getCodeById(e.getKey()),
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));

Also, a keySet of the initial map may be iterated upon:

// or using keySet()
Map<Code, List<ObjectOne>> mapByCode2 = initialMap
.keySet()
.stream() // Stream<ID>
.collect(Collectors.groupingBy(
repository::getCodeById,
Collectors.mapping(initialMap::get, Collectors.toList())
));

Is it possible to initialize `List` with a value on method call

The reason you can't do addToMe(new ArrayList<String>().add("Test Element")); is because add(E) isn't designed for fluent style programming: it returns a boolean, not the original list with an added element.

Option 1: Anonymous type with initializer block*

new ArrayList<String>(){{ add("Test Element"); }}

In your code:

void addToMe(new ArrayList<String>(){{ add("Test Element"); }})

This is read+write and still a List<String> so you can treat it as such without problems, (warning: there are subtle consequences to this, as the type returned by getClass() on that list won't be java.util.ArrayList now, it will instead be an anonymous class type).

Option 2: use the (dangerous) Arrays.asList(String... args)

Alternatively if you only need a List<String>, and it doesn't need to be writeable you could use Arrays#asList. But: be careful. This is a fixed size list. Adding more items to it will throw an UnsupportedOperationException:

void addToMe(Arrays.asList("Test Element1", "Test Element2"));

Option 3: use the JCF "copy" constructor

In the documentation for Collection<E> in the JCF, it states:

All general-purpose Collection implementation classes ... should provide ... a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Therefore, if you use this with Arrays.asList(String... args), you can do:

    void addToMe(new ArrayList<String>(Arrays.asList("Test Element1", "Test Element2")));

But this is ugly and hard to read, so I recommend splitting it up into more than one line. The advantage over just using Arrays.asList is that it is read+write and not fixed size.

Initialization of an ArrayList in one line

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.



Related Topics



Leave a reply



Submit