Java init list of string

6 ways to Initialize List of String in Java

In this post, I will be sharing how to initialize List of String in Java. There are six ways to achieve our goal:
1. Using ArrayList
2. Using Java 8 Stream.of()
3. Using Java 9 List.of()
4. Using Array’s asList() method
5. Using ArrayList add() method
6. Using Guava library

1. Initialize List of String Without Values

1. Using ArrayList

ListString> list1 = new ArrayList<>(); 
ListString> list2 = new LinkedList<>(); 

2. Initialize List of String With Values

2. Using Java 8 Stream.of()

import java.util.*; import java.util.stream.*; public class InitializeListOfString < public static void main(String args[]) < // Using Java 8 List fruits = Stream.of("Apple", "Banana", "Orange").collect(Collectors.toList()); System.out.println(fruits); > >

Output:
[Apple, Banana, Orange]

3. Using Java 9 List.of()

List.of() method is introduced in Java 9. It can be used to initialize the list of string with values as shown below:

import java.util.List; public class InitializeListOfString2 < public static void main(String args[]) < // Using Java 9 List fruits = List.of("Apple", "Blackberry", "Strawberry"); System.out.println(fruits); > >

Output:
[Apple, Blackberry, Strawberry]

4. Using Arrays.asList() method

You can use Arrays class asList() method to initialize the list of string with values as shown below:

import java.util.*; public class InitializeListOfString3 < public static void main(String args[]) < // Using Arrays.asList() method List fruits = Arrays.asList("Apple", "Grape", "Pear"); System.out.println(fruits); > >

Output:
[Apple, Grape, Pear]

5. Using ArrayList class add() method

You can also use ArrayList class add() method to initialize list of string with values as shown below:

import java.util.*; public class InitializeListOfString4 < public static void main(String args[]) < // Using ArrayList class add() method List fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Guava"); fruits.add("Litchi"); System.out.println(fruits); > >

Output:
[Apple, Guava, Litchi]

6. Using Guava library

import static com.google.common.collect.Lists.newArrayList; public class InitializeListOfString5 < public static void main(String args[]) < // Using Guava library newArrayList method ListString> fruits = newArrayList("Apple", "Pomegranate", "Banana"); System.out.println(fruits); > >

Output:
[Apple, Pomegranate, Banana]

3. Complete Example

Below is the complete example:

import java.util.*; import java.util.stream.*; public class InitializeListOfStringComplete < public static void main(String args[]) < // Using Java 9 List.of() method ListString> fruits = List.of("Apple", "Blackberry", "Strawberry"); System.out.println(fruits); // Using Java 8 Stream.of() method ListString> fruits2 = Stream.of("Apple", "Banana", "Orange").collect(Collectors.toList()); System.out.println(fruits2); // Using Arrays.asList() method ListString> fruits3 = Arrays.asList("Apple", "Grape", "Pear"); System.out.println(fruits3); // Using ArrayList class add() method ListString> fruits4 = new ArrayList<>(); fruits4.add("Apple"); fruits4.add("Guava"); fruits4.add("Litchi"); System.out.println(fruits4); > >

Output:
[Apple, Blackberry, Strawberry]
[Apple, Banana, Orange]
[Apple, Grape, Pear]
[Apple, Guava, Litchi]

Читайте также:  Css adjust all font sizes

That’s all for today. Please mention in the comments in case you have any questions related to different ways to initialize list of string in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Java List Initialization in One Line

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Читайте также:  Python object shared memory

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’ll investigate how to initialize a List using one-liners.

Further reading:

Collections.emptyList() vs. New List Instance

Guide to the Java ArrayList

2. Create From an Array

We can create a List from an array. And thanks to array literals, we can initialize them in one line:

List list = Arrays.asList(new String[]);

We can trust the varargs mechanism to handle the array creation. With that, we can write more concise and readable code:

@Test public void givenArraysAsList_thenInitialiseList() < Listlist = Arrays.asList("foo", "bar"); assertTrue(list.contains("foo")); >

The result instance of this code implements the List interface, but it isn’t a java.util.ArrayList or a LinkedList. Instead, it’s a List backed by the original array, which has two implications that we’ll look at in the rest of this section.

Although the class’s name happens to be ArrayList, it’s in the java.util.Arrays package.

2.1. Fixed Size

The result instance from Arrays.asList will have a fixed size:

@Test(expected = UnsupportedOperationException.class) public void givenArraysAsList_whenAdd_thenUnsupportedException() < Listlist = Arrays.asList("foo", "bar"); list.add("baz"); >

2.2. Shared Reference

The original array and the list share the same references to the objects:

@Test public void givenArraysAsList_whenCreated_thenShareReference()< String[] array = ; List list = Arrays.asList(array); array[0] = "baz"; assertEquals("baz", list.get(0)); >

3. Create From a Stream (Java 8)

We can easily convert a Stream into any kind of Collection.

Therefore, with the factory methods for Streams, we can create and initialize lists in one line:

@Test public void givenStream_thenInitializeList() < Listlist = Stream.of("foo", "bar") .collect(Collectors.toList()); assertTrue(list.contains("foo")); >

We should note here that Collectors.toList() doesn’t guarantee the exact implementation of the returned List.

There’s no general contract about the mutability, serializability or thread safety of the returned instance. So, our code shouldn’t rely on any of these properties.

Читайте также:  Ход короля питон тьютор решение

Some sources highlight that Stream.of(…).collect(…) may have a larger memory and performance footprint than Arrays.asList(). But in almost all cases, it’s such a micro-optimization that there is little difference.

4. Factory Methods (Java 9)

JDK 9 introduces several convenient factory methods for collections:

List list = List.of("foo", "bar", "baz"); Set set = Set.of("foo", "bar", "baz");

One important detail is that the returned instances are immutable. Beyond that, the factory methods have several advantages in space efficiency and thread safety.

This topic is explored more in this article.

5. Double-Brace Initialization

In several places, we can find a method called double-brace initialization, which looks like this:

@Test public void givenAnonymousInnerClass_thenInitialiseList() < Listcities = new ArrayList() >; assertTrue(cities.contains("New York")); >

The name “double-brace initialization” is quite misleading. While the syntax may look compact and elegant, it dangerously hides what is going on under the hood.

There isn’t actually a double-brace syntax element in Java; those are two blocks formatted intentionally this way.

With the outer braces, we declare an anonymous inner class that will be a subclass of the ArrayList. We can declare the details of our subclass inside these braces.

As usual, we can use instance initializer blocks, and that is where the inner pair of braces comes from.

The brevity of this syntax is tempting. However, it’s considered an anti-pattern.

To read more about double-brace initialization, have a look at our article here.

6. Conclusion

Modern Java offers several options to create a Collection in one line. The method we choose is almost entirely down to personal preference rather than technical reasoning.

An important takeaway is that, although it looks graceful, the anti-pattern of anonymous inner class initialization (aka double brace) has many negative side effects.

As always, the code is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью