Java conversion all to string

12 Methods to Convert a List to String in Java

convert list to string in java

Looking to convert List to String in Java? Let’s have a look at how to convert a Java Collections List of elements to a String in Java. In this post, we have talked about these best 12 methods of convert list string in java, you can learn and also implement it easily.

To Convert a list to string in java, You can do by,

1. Using toString()
2. List Of Object To String
3. Join Method(StringUtils)
4. Stream Collectors
5. Comma Separator(delimiter)
6. Convert Character List To String
7. With Double Quotes
8. Sort Method
9. toJSON Method
10. The method in Java 8
11. ReplaceAll Method
12. LinkList to String

Introduction to Convert List to String in Java

Basically List in Java is an ordered collection or a default sequence.

List accepts duplicate elements unlike Map doesn’t accept duplicate values and also holds the object in key-value pairs.

We can print the contents of a List element in a readable form while debugging the code, which is helpful.

List interface and String class were part of Java object-oriented programming API.

Читайте также:  Python работа с kivy

We can add any type of Java object to a List. If the List does not type, then using Java Generics we can apply objects of various types in the same List.

Typically we will enclose the generic type in square brackets.

  • 1 Introduction to Convert List to String in Java
  • 2 Using toString()
  • 3 List of Object to String
  • 4 Join Method (StringUtils)
  • 5 Stream Collectors
  • 6 Comma Separator(delimiter)
  • 7 Convert Character List to String
  • 8 with Double Quotes
  • 9 Sort Method
  • 10 toJson Method
  • 11 In Java 8
  • 12 replaceAll Method
  • 13 LinkedList to String

Using toString()

From the below Java program, let’s see how to convert Java list to string array using the toString method.

We are passing an integer argument(number) to create a java string array using the Java Arrays asList() method.

In other words, we are passing a list of integers as an array to list.

public static void main(String[] args) < try < Listlist = Arrays.asList(0, 1, 2, 3); System.out.println(list); > catch (Exception e) < e.printStackTrace(); >> Output: [0, 1, 2, 3] 

As per the output code above, we can see a list of array values printed as an array of strings or string array in java.

This way of implementation uses the inbuilt toString() method within the List.

Here Integer Java generics type has an internal implementation of the toString() method.

In the above example, we used Arrays.asList to create an array in java in an optimal manner.

But we can also use standard ArrayList in java and can add the values using the list.add() method or addAll method.

Also, we can convert from traditional ArrayList to String Array using ArrayList Class.

Interview Question 1 -> Primitive Types in Java:

boolean, byte, char, short, int, long, float, and double are the primitive types in Java API.

List of Object to String

Let’s see how Object toString() method works as per below java program class.

public class HelloObject < String name; int age; public String getName() < return name; >public void setName(String name) < this.name = name; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >@Override public String toString() < return "HelloObject [name=" + name + ", age=" + age + "]"; >> 

Here the custom toString() function which returns in a custom string object format.

public static void main(String[] args) < try < List list = new ArrayList(); HelloObject hb = new HelloObject(); hb.setName("James"); hb.setAge(25); list.add(hb); System.out.println(List); > catch (Exception e) < e.printStackTrace(); >> Output: [HelloObject [name=James, age=25]] 

Here custom toString() in the HelloObject will convert the Object into String representation format.

As per output, we can see the list of string.

Interview Question 2 -> ArrayList vs LinkedList:

Array List in java API applies a dynamic array to store the elements.

Whereas LinkedList uses a double linked list to store the elements.

Also, the ArrayList String value can convert to a byte array using the Java programming language.

Again both ArrayList and LinkedList accept duplicate values.

But we can remove duplicates using plain Java code, Lambdas, Guava.

Join Method (StringUtils)

We can use the join method of Apache Commons Lang StringUtils class to achieve the java list to string conversion.

public static void main(String[] args) < try < Listlist = Arrays.asList(0, 1, 2, 3); System.out.println(StringUtils.join(list, " ")); > catch (Exception e) < e.printStackTrace(); >> Output: 0 1 2 3 

StringUtils.join method have inbuilt toString() method.

As we can see from the above output, it prints the List elements as String data type with space delimiter.

we can also use java regular expressions to define a search pattern for strings.

A regular expression is best applicable for pattern matching of expressions or functions.

Here is the maven dependency for Apache commons-lang StringUtils class of java API.

you can use this in your project pom.xml file as a dependency.

  org.apache.commons commons-lang3 3.9   

The latest version of the dependency will be available here.

Stream Collectors

convert list to string in java

Now let’s use the Java Util Stream Collectors API package to convert List to String.

Here we leverage Java streams method stream() for conversion.

public static void main(String[] args) < try < Listlist = Arrays.asList(1, 2, 3); String result = list.stream(). map(i -> String.valueOf(i)). collect(Collectors.joining("/", "(", ")")); System.out.println(result); > catch (Exception e) < e.printStackTrace(); >> Output: (1/2/3) 

In the above example, we can see the usage of the stream(). map, note that it is different from standard java map.

Comma Separator(delimiter)

Let’s go through how to convert using comma-separated values.

public static void main(String[] args) < try < Listcountries = Arrays.asList("USA", "UK", "Australia", "India"); String countriesComma = String.join(",", countries); System.out.println(countriesComma); > catch (Exception e) < e.printStackTrace(); >> Output: USA,UK,Australia,India 

As per the output above, we can see conversion using delimiter i,e. separated by Comma or Comma separated.

Using join method, you can convert List to String with Separator comma, backslash, space, and so on.

Convert Character List to String

Let’s go through how to convert List of Characters to String using StringBuilder class.

public static void main(String[] args) < try < Listlist = Arrays.asList('c', 's', 'v'); StringBuilder sb = new StringBuilder(); for (Character chr : list) < sb.append(chr); >// convert to string String result = sb.toString(); System.out.println(result); > catch (Exception e) < e.printStackTrace(); >> Output: csv 

with Double Quotes

Using Apache Commons StringUtils package, convert List to String with Quotes using Java.

Refer to the below implementation

public static void main(String[] args) < try < Listcountries = Arrays.asList("USA", "UK", "Australia", "India"); String join = StringUtils.join(countries, "\", \""); String wrapQuotes = StringUtils.wrap(join, "\""); System.out.println(wrapQuotes); > catch (Exception e) < e.printStackTrace(); >> Output: "USA", "UK", "Australia", "India" 

Of course, you can convert using Single Quotes with Single String as well.

Sort Method

we can convert using Java Sort with the below implementation.

public static void main(String[] args) < try < Listcountries = Arrays.asList("USA", "UK", "Australia", "India"); countries.sort(Comparator.comparing(String::toString)); System.out.println(countries); > catch (Exception e) < e.printStackTrace(); >> Output: [Australia, India, UK, USA] 

toJson Method

Let’s convert List to String JSON in Java using Google GSON library.

It is a straight forward method ToJson() which will set and convert the input to JSON String.

public static void main(String[] args) < try < Listcountries = Arrays.asList("USA", "UK", "Australia", "India"); String json = new Gson().toJson(countries); System.out.println(json); > catch (Exception e) < e.printStackTrace(); >> Output: ["USA","UK","Australia","India"] 

In Java 8

Let’s convert List to String using String.join() method in Java 8.

public static void main(String[] args) < try < Listlist = Arrays.asList("USA", "UK", "INDIA"); String delimiter = "-"; String result = String.join(delimiter, list); System.out.println(result); > catch (Exception e) < e.printStackTrace(); >> Output: USA-UK-INDIA 

replaceAll Method

Lets convert List to String using replaceAll() and String.join() method.

You can also notice inline lambda expressions used in the replaceAll method.

public static void main(String[] args) < try < Listcountries = Arrays.asList("usa", "uk", "india"); countries.replaceAll(r -> r.toUpperCase()); String result = String.join(" ", countries); System.out.println(result); > catch (Exception e) < e.printStackTrace(); >> Output: USA UK INDIA 

LinkedList to String

Let’s convert LinkedList to String using String.join() method.

public static void main(String[] args) < try < LinkedListlist = new LinkedList(); list.add("USA"); list.add("UK"); list.add("INDIA"); String result = String.join(" ", list); System.out.println(result); > catch (Exception e) < e.printStackTrace(); >> Output: USA UK INDIA 

In case of any issues during conversion, we can notice the error message in the console log.

To conclude, in this tutorial we gone through different ways to convert a Java List to String data type.

List to String methods conversion is also common in other programming languages like JavaScript, Python, Jquery.

In a nutshell, JavaScript uses an str function for concatenate, likewise, the python program uses join method for conversion and concatenate a string.

Interested to read JavaScript resources, check out this JavaScript split method article.

Keeping sharing java tutorials and happy coding 🙂

Источник

Java String Array to String

Java String Array to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into how to convert Java String array to String. Sometimes we have to convert String array to String for specific requirements. For example; we want to log the array contents or we need to convert values of the String array to String and invoke other methods.

Java String Array to String

Most of the time we invoke toString() method of an Object to get the String representation. Let’s see what happens when we invoke toString() method on String array in java.

package com.journaldev.util; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] ; String str = strArr.toString(); System.out.println("Java String array to String = "+str); > > 

java string array to string toString method call output

Below image shows the output produced by the above program. The reason for the above output is because toString() call on the array is going to Object superclass where it’s implemented as below.

Java String Array to String Example

So how to convert String array to String in java. We can use Arrays.toString method that invoke the toString() method on individual elements and use StringBuilder to create String.

public static String toString(Object[] a) < if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) < b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); >> 

We can also create our own method to convert String array to String if we have some specific format requirements. Below is a simple program showing these methods in action and output produced.

package com.journaldev.util; import java.util.Arrays; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] < "1", "2", "3" >; String str = Arrays.toString(strArr); System.out.println("Java String array to String = " + str); str = convertStringArrayToString(strArr, ","); System.out.println("Convert Java String array to String = " + str); > private static String convertStringArrayToString(String[] strArr, String delimiter) < StringBuilder sb = new StringBuilder(); for (String str : strArr) sb.append(str).append(delimiter); return sb.substring(0, sb.length() - 1); >> 

convert string array to string in java

So if we use array toString() method, it returns useless data. Java Arrays class provide toString(Object[] objArr) that iterates over the elements of the array and use their toString() implementation to return the String representation of the array. That’s why when we use this function, we can see that it’s printing the array contents and it can be used for logging purposes. If you want to combine all the String elements in the String array with some specific delimiter, then you can use convertStringArrayToString(String[] strArr, String delimiter) method that returns the String after combining them.

Java Array to String Example

Now let’s extend our String array to String example to use with any other custom classes, here is the implementation.

package com.journaldev.util; import java.util.Arrays; public class JavaArrayToString < public static void main(String[] args) < A[] arr = < new A("1"), new A("2"), new A("3") >; // default toString() method System.out.println(arr.toString()); // using Arrays.toString() for printing object array contents System.out.println(Arrays.toString(arr)); // converting Object Array to String System.out.println(convertObjectArrayToString(arr, ",")); > private static String convertObjectArrayToString(Object[] arr, String delimiter) < StringBuilder sb = new StringBuilder(); for (Object obj : arr) sb.append(obj.toString()).append(delimiter); return sb.substring(0, sb.length() - 1); >> class A < private String name; public A(String name) < this.name = name; >@Override public String toString() < System.out.println("A toString() method called!!"); return this.name; >> 
[Lcom.journaldev.util.A;@7852e922 A toString() method called!! A toString() method called!! A toString() method called!! [1, 2, 3] A toString() method called!! A toString() method called!! A toString() method called!! 1,2,3 

So we looked at how to convert Java String array to String and then extended it to use with custom objects. That’s all for converting java array to String. You can checkout more core java examples from our GitHub Repository. Reference: Java Arrays toString API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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