0

I have a string that values are separated by commas, for example: "pizza,hamburguer,fries"

I need to iterate the String and add each value into a List, how can I do that? If there's a comma add the value into the list before the comma.

Thanks in advance,

String s = "pizza,hamburguer,fries";
ArrayList<String> list = new ArrayList();

list.add("pizza");
list.add("hamburuger");
list.add("fries");

4 Answers4

0

This is not exactly a duplicate since you want an ArrayList.

First split the String into an Array and then declare a new ArrayList from that array using Arrays.asList(arr).

    String s = "pizza,hamburguer,fries";

    String[] arr = s.split(",");
    ArrayList<String> list = new ArrayList(Arrays.asList(arr));
Nexevis
  • 4,647
  • 3
  • 13
  • 22
0

You can you the String.split() method:

String s = "pizza,hamburguer,fries";
String[] splitArray = s.split(",");
List<String> list = Arrays.asList(splitArray);

list.add("pizza");
list.add("hamburuger");
list.add("fries");
ksaf
  • 41
  • 4
0

Something like this?

    String s = "pizza,hamburguer,fries";
    ArrayList<String> list = new ArrayList();
    String[] aux = s.split(",");

    for(int i = 0; i < aux.length; ++i)
    {
        list.add(aux[i]);
    }
Ricardo
  • 23
  • 5
0

I'm not very sure whether this is the best way to solve this problem. But do give this a try:

import java.io.*;
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        String s = "pizza,hamburguer,fries";
        ArrayList<String> List = new ArrayList<String>();
        for(String word : s.split(",")) {
            List.add(word);
            }
            int len= List.size();
            System.out.println(len);

            for (String str : List) {
            System.out.println(str);
        }

    }
}
Alen S Thomas
  • 923
  • 7
  • 10