How To Convert String To List In Java

In Java, the string is the primitive data type that stores a sequence of characters and allows the programmer to store the data in the system. Strings are commonly used in every application to take user input or to store data from the user. Also, strings are immutable means they are not accessible directly.

The list is the data structure from the collection class which stores the data in the sequence of objects. Lists are mutable which means that they can be accessed directly. A list is commonly used to save the data in a sequence or in a key-value pair. The list helps in accessing the data easily and to make the modification by using methods.

As we have already discussed, strings are immutable. To make the string data mutable or more accessible, the program has to convert string data into a list. Also, if a programmer wants to insert or delete the data in any sequence, he or she has to use a list.

Hence, converting the string input to a list is an essential task in programming. Now, we are going to discuss “how to convert string to list in Java”.

Why Is There A Need To Convert String To List In Java

Before discussing the conversion, we will try to understand why programmers need to convert strings into the list. Is there any real-life application? Where can it be used and how does it work?

Let us discuss some reasons to convert string to list in Java.

  1. Immutable list: As stated above, strings are immutable. If the programmer converts the immutable string to a list then the list also becomes immutable. Hence, the list of data can’t be accessed directly. But, programmers can use list methods on the data.
  2. Assessing multiple values: In string at a time we can access only one object. But in the list, multiple data sets can be accessed. This helps in assessing more data values at a time and increases the programmer’s productivity.
  3. Managing individual values: In a list, programmers can access each character through the index value but, in a string this facility is unavailable. Lists index each value to apply different methods to the data.
  4. Performing operations: Converting strings to lists helps to perform operations on a set of strings and apply different methods to achieve the desired results as per the scenario. Programmers can split the string or do more operations with more flexibility on each value.
  5. Data manipulation: Lists are more convenient and helpful to handle the data. Also, it helps in data manipulation by different methods which are commonly used in real-life applications. Hence, lists are more convenient in data handling and manipulation compared to strings.
  6. Converting to advanced data structures: Lists are easy to be converted into advanced data structures like sets and hashmap that helps in a high level of data handling and create an application on the next level.

These are some reasons to convert strings into lists and make data manipulation more simple and convenient. More reasons can be added to this situation as more scenarios can take place in the programming world.

This makes this topic more important in Java. Now let us move on “how to convert string to list in Java”.

Different Approaches To Convert Strings to Lists in Java

As we have already discussed, converting strings to lists has many applications in the real-life app development process. Now, we are going to discuss different approaches to achieving conversion.

Also, we will also recommend the best approach for the programmers to get the best results. Different approaches are as follows:

  1. Using split() method
  2. Using asList() method
  3. Using StringTokenizer
  4. Using streams
  5. Using Guava class

These five approaches will be discussed below with proper explanation and briefing of the topic to get exact and useful knowledge to the reader. Also, a sample code and its explanation will be given to deep dive into the topic. Sample problems will be provided for practicing the conversion.

Overall, this article is going to test your basics in Java and make you a more advanced programmer.  Let us understand “how to convert string to list in Java” with brief explanations and code.

Approach 1 : Convert the string to a list using the split() method

This is the most common method to convert a string to a list. The split() method splits the string into an array and then the array can be converted to the list using the asList() method. Code and its explanation given below –

Sample code :

public class Main {
    public static void main(String[] args) {
        
        // create a string and insert the values
        String str = "apple,banana,orange";
        
        // then split the string using loop and split() method 
        String[] arr = str.split(",");
        for (String s : arr) {
            
            // print the output on the console
            System.out.println(s);
        }
    }
}

Output :

apple
banana
orange

Explanation :

  1. Create a string and insert the values.
  2. Use the split() value to split the string using loop
  3. Print the list values using a loop.

Approach 2 : Convert the string to a list using the asList() method

This method is applied using the split() method. split() method, splits the string values and asList() method converts the string into a list. This method is implemented using java.util.Arrays, java.util.List libraries. This is also an appropriate method for conversion.

Sample code :

// import the necessary libraries
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        
        // create a string with some values
        String str = "apple,banana,orange";
        
        // use the methods to split() and convert the string into list
        List<String> list = Arrays.asList(str.split(","));
        
        // print the output on console
        System.out.println(list);
    }
}

Output :

[apple, banana, orange]

Explanation :

  1. Import the java.util.Arrays, java.util.List libraries to implement the methods.
  2. Create a string with some values.
  3. Use the split() method to split the string.
  4. Use the asList() method to convert each string into a list.
  5. Print the output on the console.

Approach 3 : Convert the string to a list using the StringTokenizer

In Java, StringTokenizer is the class that can be used to split the strings and then the split tokens are added to a list. java.util.StringTokenizer is the library that helps in the implementation of StringTokenizer class.

Sample code :

// import the necessary libraries
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
        
        // create a string with some values
        String str = "apple,banana,orange";
        
        // create a new and empty list
        List<String> list = new ArrayList<>();
        
        // using the StringTokenizer class split the string
        StringTokenizer token = new StringTokenizer(str, ",");
        
        // use loop to add split string tokens into the empty list
        while (token.hasMoreTokens()) {
            list.add(token.nextToken());
        }
        
        // print the output on the console
        System.out.println(list);
    }
}

Output :

[apple, banana, orange]

Explanation :

  1. Import the necessary libraries as shown in the code.
  2. Create a string with some values.
  3. Create an empty list.
  4. Use the StringTokenizer class to split the string.
  5. Then add the string values into the list by using loops and hasMoreTokens(), nextToken() methods.
  6. Then print the output on the console.

Approach 4 : Convert the string to a list using the streams

In Java, streams are the sequence of objects which can be used to apply various methods to get desired results. Streams are ve powerful during the conversion operations. Many conversions can be carried out through the stream methods. Let us convert the strings into lists using Stream methods.

Sample code :

// import the necessary libraries
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // create a string with some values
        String str = "apple,banana,orange";
        
        // split the string and add them to list using some methods
        List<String> list = Arrays.stream(str.split(","))
                                  .collect(Collectors.toList());
                                  
        // print the output on the console
        System.out.println(list);
    }
}	

Output :

[apple, banana, orange]

Explanation :

  1. Import the necessary libraries including java.util.stream.Collectors.
  2. Create a string with some values to insert into the list.
  3. Split the string using the str.split() method.
  4. Then add the values to the list using the Collectors.toList() method.
  5. Then print the output on the console.

Approach 5 : Convert the string to a list using the Guava class

Guava is the open-source library that provides prewritten code for some common Java programs. Its utility classes help the programmer to save time by copy-pasting the code for some common tasks. The splitter class in Guava is used to split the string values and add them to the list.

To run this code we have to install exclusive guava library and set the environment variable. This library is not supported by online compilers.

Sample code :

// import the necessary libraries
import com.google.common.base.Splitter;
import java.util.List;

public class Main {
    public static void main(String[] args) {
         // create a string with some values
        String str = "apple,banana,orange";
        
        // use the splitter class and its method for the conversion
        List<String> list = Splitter.on(",")
                                    .trimResults()
                                    .splitToList(str);
                                    
        // print the output on the console
        System.out.println(list);
    }
}

Output :

[apple, banana, orange]

Explanation :

  1. Import the libraries including com.google.common.base.Splitter.
  2. Create a string with some values.
  3. Using the Splitter class, split the string values.
  4. Then, use the splitToList() method to convert the string into a list.
  5. Finally, print the output on the console.

Best Approach Out Of Five For Converting string to list in Java

We have discussed five methods for “how to convert string into list in java”. All these approaches are appropriate for achieving the conversion. But, the split() method is the best approach for the conversion of string values to the list.

Why did we consider the split() method as the best approach? Here are some reasons for the same:

  1. Beginner friendly: This method is beginner friendly as to understand the method no advanced knowledge of Java is required and can be executed easily. Also, it is the simplest among the five approaches.
  2. Concise: The lines of code are fewer comparing the other four approaches. This reduces the complexity of the program and makes it easy to understand.
  3. Fewer methods are used: In this approach, only one method is implemented for the conversion by using a loop. This makes it a more concise and sweet and short method.
  4. No extra libraries : This approach doesn’t require extra library implementation which reduces the dependency on external factors. This helps to implement the method within the environment and reduces the chances of failure.
  5. Implemented efficiently : This method is implemented efficiently on any string and achieves the desired results. This helps the programmer to implement the method in any application development file.

These are some reasons to choose the split() method as the best approach. But, a good programmer has to practice and understand all the approaches to increase his knowledge horizon as other approaches can be used in other tasks.

Understanding and implementing all the approaches will help the programmer to achieve better coding practice and increase his understanding of basic and advanced topics.

Sample Problems

Sample problem 1

Create a program that takes the list of items that a customer wants to buy from the shop and displays the list on the bill. Convert the string to a list using the split() method.

Solution :

1.	Get the list of items from the customer.
2.	Use the split() value to split the string using loop
3.	Print the list values using a loop on a bill

Code :

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        // get the list of items from the customer
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a comma-separated list of values:");
        String str = scanner.nextLine();
        
        // then split the string using loop and split() method 
        String[] arr = str.split(",");
        for (String s : arr) {
            
            // print the output on the console
            System.out.println(s);
        }
    }
}

Output :

Enter a comma-separated list of values: Hair-Oil,Vegetable Oil,Rice,Chocolates

Hair-Oil
Vegetable Oil
Rice
Chocolates

Sample problem 2

Create a program that takes the list of cars that arrived from the dealer to the showroom and displays the list of cars in the report. Convert the string to a list using the asList() method.

Solution :

  1. Import the java.util.Arrays, java.util.List libraries to implement the methods.
  2. Get the list of cars from the dealer.
  3. Use the split() method to split the string.
  4. Use the asList() method to convert each string into a list.
  5. Display the list of cars.

Code :

// import the necessary libraries
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
         // get the list of cars from the dealer
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a comma-separated list of values:");
        String str = scanner.nextLine();
        
        // use the methods to split() and convert the string into a list
        List<String> list = Arrays.asList(str.split(","));
        
        // print the output on the report
        System.out.println(list);
    }
}

Output :

Enter a comma-separated list of values:
Maruti Alto 800,Maruti Alto K10,Maruti S-Presso
[Maruti Alto 800, Maruti Alto K10, Maruti S-Presso]

Sample problem 3

Create a program that gets the name of students who have achieved the first position in the respective section and save them in the database. Convert the string to a list using the StringTokenizer approach.

Solution :

  1. Import the necessary libraries as shown in the code.
  2. Create a string with some values.
  3. Create an empty list.
  4. Use the StringTokenizer class to split the string.
  5. Then add the string values into the list by using loops and hasMoreTokens(), and nextToken() methods.
  6. Then save the data in the database.

Code :

// import the necessary libraries
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        
        // get the list of students who ranked first in their respective class
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a comma-separated list of values:");
        String str = scanner.nextLine();
        
        // create a new and empty list
        List<String> list = new ArrayList<>();
        
        // using the StringTokenizer class split the string
        StringTokenizer token = new StringTokenizer(str, ",");
        
        // use loop to add split string tokens into the empty list
        while (token.hasMoreTokens()) {
            list.add(token.nextToken());
        }
        
        // print the output on the console
        System.out.println(list);
    }
}

Output :

Enter a comma-separated list of values:
Manish,Sparsh,Nikhil,Meeenal
[Manish, Sparsh, Nikhil, Meeenal]

Sample problem 4

Create a program that registers the name of the participants in a badminton competition and share the list with the event organizer. Convert the string to a list using the Stream methods.

Solution :

  1. Import the necessary libraries including java.util.stream.Collectors.
  2. Get the name of the participants in the form of a string.
  3. Split the string using the str.split() method.
  4. Then add the values to the list using the Collectors.toList() method.
  5. Then print the output on the console and share it with the event organizer.

Code :

// import the necessary libraries
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       // get the list of the students who want to participate in badminton competition
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a comma-separated list of values:");
        String str = scanner.nextLine();
        
        // split the string and add them to list using some methods
        List<String> list = Arrays.stream(str.split(",")Enter a comma-separated list of values:
Rohit,Tejas,Suraj,Devidas
[Rohit, Tejas, Suraj, Devidas]

                                  .collect(Collectors.toList());
                                  
        // print the output on the console
        System.out.println(list);
    }
}

Output :

Enter a comma-separated list of values:
Rohit,Tejas,Suraj,Devidas
[Rohit, Tejas, Suraj, Devidas]

Sample problem 5

Create a program that takes the list of teachers who have attained the teacher training program and mail the list to the principal of the school. Convert the string to a list using the Guava class.

Solution :

  1. Import the libraries including com.google.common.base.Splitter.
  2. Create a string with some values.
  3. Using the Splitter class, split the string values.
  4. Then, use the splitToList() method to convert the string into a list.
  5. Finally, print the output on the console.

Code :

// import the necessary libraries
import com.google.common.base.Splitter;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // get the list of the teachers who attained the teacher's training program
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a comma-separated list of values:");
        String str = scanner.nextLine();
        
        // use the splitter class and its method for the conversion
        List<String> list = Splitter.on(",")
                                    .trimResults()
                                    .splitToList(str);
                                    
        // print the output on the console
        System.out.println(list);
    }
}

Output :

Enter a comma-separated list of values:
Lubna,Shashikala,Chandramukhi
[Lubna, Shashikala, Chandramukhi]

Conclusion

Purpose of the conversion of the string data into a list is to handle and manipulate the data in an efficient manner. Real-life applications store bulk data on the database, which cannot be maintained with the strings as they have few methods and immutable properties. In this scenario, the list comes to rescue the programmers, with advanced methods and more accessibility to the data. Many other benefits of the list over string are already discussed below.

We have discussed five methods including the split() method, asList() method, StringTokenizer, streams, and the Guava class methods. All these methods are efficient and can be used in real applications for achieving the conversion of the string to the list. Also, the split() method is recommended as the best approach because of its programmer-friendly and simple nature.

A programmer should dive into the topic to expand their learning horizon and also practice the code to become an advanced programmer. Hope, this article will help every reader individually to understand “how to convert string into list in Java”.