Java list string convert to string array

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!

Источник

How To Convert ArrayList To String Array In Java 8 — toArray() Example

Twitter Facebook Google Pinterest

A quick guide on how to convert ArrayList to String[] array in Java. How to convert List of Strings into String[] using Java 8 Stream api.

1. Overview

In this article, You’re going to learn how to convert ArrayList to String[] Array in Java. ArrayList is used to store the List of String using the toArray() and Stream API toArray() method.

How To Convert ArrayList To String Array In Java 8 - toArray() Example

2. ArrayList to String Without Using API Methods

This is a simple approach by running a for loop from index 0 to the last index of the ArrayList and next Create a new String with the size of ArrayList size.

Finally, assign each index value from ArrayList to String array at the same index.

Look at the below example program. Read the comments given in the program

package com.javaprogramto.java8.arraylist.toarray; import java.util.ArrayList; import java.util.List; public class NormalApproach < public static void main(String[] args) < // Created a List with type String ListlistOfStrings = new ArrayList<>(); // Added 5 string values to ArrayList listOfStrings.add("String One"); listOfStrings.add("String Two"); listOfStrings.add("String Three"); listOfStrings.add("String Four"); listOfStrings.add("String Five"); // Created string array with the size of List String[] stringArray = new String[listOfStrings.size()]; // Adding list values into ArrayList for (int i = 0; i // Printing the values of Array. for (int i = 0; i < stringArray.length; i++) < System.out.println("String value at index "+i+" is "+stringArray[i]); >> >
String value at index 0 is String One String value at index 1 is String Two String value at index 2 is String Three String value at index 3 is String Four String value at index 4 is String Five

3. Using List.toArray() Method

List api has a builtin method to covert List to Array[] array, In our example, T is the type of String. So, When List.toArray() method is called it converts ArrayList to String array.

package com.javaprogramto.java8.arraylist.toarray; import java.util.ArrayList; import java.util.List; public class ListToArrayExample < public static void main(String[] args) < // Created a List with type String ListlistOfStrings = new ArrayList<>(); // Added 5 string values to ArrayList listOfStrings.add("String One"); listOfStrings.add("String Two"); listOfStrings.add("String Three"); listOfStrings.add("String Four"); listOfStrings.add("String Five"); // Created string array with the size of List and calling toArray() method String[] stringArray = listOfStrings.toArray(new String[listOfStrings.size()]); // Printing the values of Array. for (int i = 0; i < stringArray.length; i++) < System.out.println("String value at index "+i+" is "+stringArray[i]); >> >
String value at index 0 is String One String value at index 1 is String Two String value at index 2 is String Three String value at index 3 is String Four String value at index 4 is String Five

4. Using Java 8 Stream.toArray() Method

Java 8 Stream API is added with a toArray() method which takes IntFunction as a Functional Interface argument and returns the array with the type of value in the List.

import java.util.ArrayList; import java.util.List; public class StreamToArrayExample < public static void main(String[] args) < // Created a List with type String ListlistOfStrings = new ArrayList<>(); // Added 5 string values to ArrayList listOfStrings.add("String One"); listOfStrings.add("String Two"); listOfStrings.add("String Three"); listOfStrings.add("String Four"); listOfStrings.add("String Five"); // Using Stream api toArray() method and passing the String array object with method reference. String[] stringArray = listOfStrings.stream().toArray(String[]::new); // Printing the values of Array. for (int i = 0; i < stringArray.length; i++) < System.out.println("String value at index "+i+" is "+stringArray[i]); >> >
String value at index 0 is String One String value at index 1 is String Two String value at index 2 is String Three String value at index 3 is String Four String value at index 4 is String Five

5. Using Arrays.toArray() and Arrays.copyof() Methods

ArrayList arrayList = new ArrayList(); Object[] objectList = arrayList.toArray(); String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class); 

6. Conclusion

In this article, You’ve learned about different ways to do the conversion from ArrayList to String[] Array using java normal and Stream API methods.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick guide on how to convert ArrayList to String[] array in Java. How to convert List of Strings into String[] using Java 8 Stream api.

Источник

Читайте также:  Jar file to java code
Оцените статью