Arraylist element to string java

Converting a List to String in Java

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.

Читайте также:  Login Page

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:

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. Introduction

In this quick tutorial, we’ll explain how to convert a List of elements to a String. This can be useful in certain scenarios, like printing the contents to the console in a human-readable form for inspection/debugging.

2. Standard toString() on a List

One of the simplest ways is to call the toString() method on the List:

@Test public void whenListToString_thenPrintDefault() < ListintLIst = Arrays.asList(1, 2, 3); System.out.println(intLIst); >

This technique internally utilizes the toString() method of the type of elements within the List. In our case, we’re using the Integer type, which has a proper implementation of the toString() method.

If we’re using our custom type, such as Person, then we need to make sure that the Person class overrides the toString() method and doesn’t rely on the default implementation. If we don’t properly implement the toString() method, we might get unexpected results:

[[email protected], [email protected], [email protected]]

3. Custom Implementation Using Collectors

Often, we might need to display the output in a different format.

Compared to the previous example, let’s replace the comma (,) with a hyphen (-), and the square brackets ([, ]) with a set of curly braces ():

@Test public void whenCollectorsJoining_thenPrintCustom() < ListintList = Arrays.asList(1, 2, 3); String result = intList.stream() .map(n -> String.valueOf(n)) .collect(Collectors.joining("-", "")); System.out.println(result); >

The Collectors.joining() method requires a CharSequence, so we need to map the Integer to String. We can utilize this same idea with other classes, even when we don’t have access to the code of the class.

4. Using an External Library

Now we’ll use Apache Commons’ StringUtils class to achieve similar results.

4.1. Maven Dependency

 org.apache.commons commons-lang3 3.11 

The latest version of the dependency can be found here.

4.2. Implementation

The implementation is literally a single method call:

@Test public void whenStringUtilsJoin_thenPrintCustom() < ListintList = Arrays.asList(1, 2, 3); System.out.println(StringUtils.join(intList, "|")); >

Again, this implementation is internally dependent on the toString() implementation of the type we’re considering.

5. Conclusion

In this article, we learned how easy it is to convert a List to a String using different techniques.

As always, the full source code for this article can be found 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:

Источник

Convert an Arraylist to a String in Java

Convert an Arraylist to a String in Java

  1. Convert ArrayList to String With + Operator in Java
  2. Convert ArrayList to String Using the append() Method in Java
  3. Convert ArrayList to String Using the join() Method in Java
  4. Convert ArrayList to String Using StringUtils Class in Java
  5. Convert ArrayList to String Using the replaceAll() Method in Java
  6. Convert ArrayList to String Using the joining() Method in Java
  7. Convert ArrayList to String Using the deepToString() Method in Java

This tutorial introduces how to convert an ArrayList to a string in Java and lists some example codes to understand the topic. There are several ways to convert ArrayList like using join() , append() method, StringUtils class, etc. Let’s take a close look at the examples.

Convert ArrayList to String With + Operator in Java

The most straightforward and easy way to convert an ArrayList to String is to use the plus (+) operator. In String, the plus operator concatenates two string objects and returns a single object. Here, we are using the plus operator. See the example below.

import java.util.ArrayList; import java.util.List;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = "";  for (String fruit : fruits)   str+= fruit+",";  >  System.out.println(str);  > > 
[Apple, Orange, Mango] Apple,Orange,Mango, 

Convert ArrayList to String Using the append() Method in Java

We can use the append() method of StringBuilder class to convert ArrayList to string. This method returns a String object. See the example below.

import java.util.ArrayList; import java.util.List;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  StringBuilder str = new StringBuilder();  for (String fruit : fruits)   str.append(fruit);  str.append(" ");  >  System.out.println(str);  > > 
[Apple, Orange, Mango] Apple Orange Mango 

Convert ArrayList to String Using the join() Method in Java

We can use the join() method of the String class to join ArrayList elements into a single string. This method returns a string and can be used to convert ArrayList to String in Java.

import java.util.ArrayList; import java.util.List;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = String.join(",", fruits);  System.out.println(str);  > > 
[Apple, Orange, Mango] Apple,Orange,Mango 

Convert ArrayList to String Using StringUtils Class in Java

If you are working with the Apache commons lang library, then you can use the join() method of StringUtils class to get string object from the ArrayList . Here, we use the join() method that takes two arguments: ArrayList and the separator symbol. See the example below.

import java.util.ArrayList; import java.util.List;  import org.apache.commons.lang3.StringUtils;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = StringUtils.join(fruits, ", ");  System.out.println(str);  > > 
[Apple, Orange, Mango] Apple, Orange, Mango 

Convert ArrayList to String Using the replaceAll() Method in Java

This is a little tricky approach to get the string from ArrayList . In this way, we use the replaceAll() method to replace square brackets of the List and then convert all elements into String using the toString() method. See the example below.

import java.util.ArrayList; import java.util.List;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = fruits.toString().replaceAll("\\[|\\]", "").replaceAll(", ",", ");  System.out.println(str);  > > 
[Apple, Orange, Mango] Apple, Orange, Mango 

Convert ArrayList to String Using the joining() Method in Java

If you are using Java 8 or higher version, you can use the joining() method of Collectors class to collect all the elements into a single String object. Here, we use the functional style of Java programming added into Java 8 version.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = Arrays.asList(fruits).stream()  .map(Object::toString)  .collect(Collectors.joining(", "));  System.out.println(str);  > > 
[Apple, Orange, Mango] [Apple, Orange, Mango] 

Convert ArrayList to String Using the deepToString() Method in Java

We can use the deepToString() method of Arrays class that converts all the elements of ArrayList into a String object. See the example below.

import java.util.ArrayList; import java.util.Arrays; import java.util.List;  public class SimpleTesting   public static void main(String[] args)   // ArrayList  ListString> fruits = new ArrayList<>();  fruits.add("Apple");  fruits.add("Orange");  fruits.add("Mango");  System.out.println(fruits);  String str = Arrays.deepToString(fruits.toArray());  System.out.println(str);  > > 
[Apple, Orange, Mango] [Apple, Orange, Mango] 

Related Article — Java String

Related Article — Java ArrayList

Источник

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