Java list string and string

Initialize List of String in java

In this post, we will see how to initialize List of String in java.

Can you initialize List of String as below:

You can’t because List is an interface and it can not be instantiated with new List() .

You need to instantiate it with the class that implements the List interface.

Here are the common java Collections classes which implement List interface.

In most of the cases, you will initialize List with ArrayList as below.

If you are using java 7 or greater than you can use diamond operator with generics.

Initialize List of Strings with values

There are many ways to initialize list of Strings with values.

Arrays’s asList

You can use Arrays’s asList method to initialize list with values.

Stream.of (Java 8)

You can use java 8‘s Stream to initialize list of String with values.

List.of (Java 9)

Finally, java has introduced a of() method in List class to initialize list with values in java 9.

Using ArrayList’s add method

You can obviously initialize ArrayList with new operator and then use add method to add element to the list.

Using guava library

You can use guava library as well.

Here is the complete example.

That’s all about how to initialize List of String in java.

Was this post helpful?

Share this

Author

Convert UUID to String in Java

Table of ContentsIntroductionUUID class in JavaConvert UUID to String in Java Introduction In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look […]

Repeat String N times in Java

Table of ContentsIntroductionWhat is a String in Java?Repeat String N times in JavaSimple For Loop to Repeat String N Times in JavaUsing Recursion to Repeat String N Times in JavaString.format() method to Repeat String N Times in JavaUsing String.repeat() method in Java 11 to Repeat String N TimesRegular Expression – Regex to Repeat String N […]

How to Replace Space with Underscore in Java

Table of ContentsReplace space with underscore in java1. Using replace() method2. Using replaceAll() method Learn about how to replace space with underscore in java. Replace space with underscore in java 1. Using replace() method Use String’s replace() method to replace space with underscore in java. String’s replace() method returns a string replacing all the CharSequence […]

How to Replace Comma with Space in Java

Table of ContentsReplace comma with space in java1. Using replace() method2. Using replaceAll() method Learn about how to replace comma with space in java. Replace comma with space in java 1. Using replace() method Use String’s replace() method to replace comma with space in java. Here is syntax of replace() method: [crayon-64ba190e1617c242018242/] [crayon-64ba190e16183936873130/] Output: 1 […]

Remove Parentheses From String in Java

Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusion Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text data at contiguous […]

Escape percent sign in java

Escape percent sign in String’s format method in java

Table of ContentsEscape Percent Sign in String’s Format Method in JavaEscape Percent Sign in printf() Method in Java In this post, we will see how to escape Percent sign in String’s format() method in java. Escape Percent Sign in String’s Format Method in Java String’s format() method uses percent sign(%) as prefix of format specifier. […]

Источник

Java 8 — Convert List to String comma separated

Convert a List in a String with all the values of the List comma separated using Java 8 is really straightforward. Let’s have a look on how to do that.

Java 8 (or above)

We simply can write String.join(..), pass a delimiter and an Iterable, then the new StringJoiner will do the rest:

ListString> cities = Arrays.asList("Milan", "London", "New York", "San Francisco"); String citiesCommaSeparated = String.join(",", cities); System.out.println(citiesCommaSeparated); // prints 'Milan,London,New York,San Francisco' to STDOUT.

In case we are working with a stream we can write as follow and still have the same result:

String citiesCommaSeparated = cities.stream() .collect(Collectors.joining(",")); System.out.println(citiesCommaSeparated); //Output: Milan,London,New York,San Francisco

Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing joining(“,”).

Java 7

For the old times’ sake, let’s have a look at Java 7 implementation.

private static final String SEPARATOR = ","; public static void main(String[] args)  ListString> cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); StringBuilder csvBuilder = new StringBuilder(); for(String city : cities) csvBuilder.append(city); csvBuilder.append(SEPARATOR); > String csv = csvBuilder.toString(); System.out.println(csv); //OUTPUT: Milan,London,New York,San Francisco, //Remove last comma csv = csv.substring(0, csv.length() - SEPARATOR.length()); System.out.println(csv); //OUTPUT: Milan,London,New York,San Francisco

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways — for example by moving the logic that removes the last comma inside the for loop — but none will be so explicative and immediate to understand as the declarative solution expressed in Java 8.

The focus should be on what you want to do — joining a List of String — not on how.

Java 8: Manipulate String before joining

Before joining you can manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in further articles. Meanwhile, this a straightforward example on how to transform the whole String in upper-case before joining them.

Java 8: From List to upper-case String comma separated

String citiesCommaSeparated = cities.stream() .map(String::toUpperCase) .collect(Collectors.joining(",")); //Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO

If you want to find out more about stream, I strongly suggest this cool video of Venkat Subramaniam.

Let’s play

The best way to learn it’s playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them 🙂

package net.reversecoding.examples; import static java.util.stream.Collectors.joining; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; public class CsvUtil  private static final String SEPARATOR = ","; public static String toCsv(ListString> listToConvert) return String.join(SEPARATOR, listToConvert); > @Test public void toCsv_csvFromListOfString() ListString> cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsv(cities)); > public static String toCsvStream(ListString> listToConvert) return listToConvert.stream() .collect(joining(SEPARATOR)); > @Test public void toCsvStream_csvFromListOfString() ListString> cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsv(cities)); > public static String toCsvJava7(ListString> listToConvert) StringBuilder csvBuilder = new StringBuilder(); for(String s : listToConvert) csvBuilder.append(s); csvBuilder.append(SEPARATOR); > String csv = csvBuilder.toString(); //Remove last separator if(csv.endsWith(SEPARATOR)) csv = csv.substring(0, csv.length() - SEPARATOR.length()); > return csv; > @Test public void toCsvJava7_csvFromListOfString() ListString> cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsvJava7(cities)); > public static String toUpperCaseCsv(ListString> listToConvert) return listToConvert.stream() .map(String::toUpperCase) .collect(joining(SEPARATOR)); > @Test public void toUpperCaseCsv_upperCaseCsvFromListOfString() ListString> cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "MILAN,LONDON,NEW YORK,SAN FRANCISCO"; assertEquals(expected, toUpperCaseCsv(cities)); > >

Reverse Coding

Traditionally teaching methods first start with theory and then move to practice. I prefer do the opposite, I find it more effective. I prefer to start from a real example, to play with that, to break it down, to ask my self some questions and only then to move to the theory. Reversecoding.net follows this approach: hope you’ll find it helpful. Thanks for visiting!

Источник

Читайте также:  Тип данных boolean php
Оцените статью