简体   繁体   中英

Converting an ArrayList to String

I am currently scraping data from a HTML table using JSoup then storing this into an ArrayList. I would then like to store these values within a SQL database. From what I understand these must be converted to a String before they can be inserted into a database. How would I go about converting these ArrayLists to a String?

Here is my current code:

    Document doc = Jsoup.connect(URL).timeout(5000).get();

    for (Element table : doc.select("table:first-of-type")) 
    {
        for (Element row : table.select("tr:gt(0)")) { 
            Elements tds = row.select("td");

            List1.add(tds.get(0).text());
            List2.add(tds.get(1).text());
            List3.add(tds.get(2).text());
        }
    }

To get all the values you need, you can iterate through the list very easily :

public static void main(String[] args) {
    List<String> List1 = new ArrayList<>();
    for (String singleString : List1){
        //Do whatever you want with each string stored in this list
    }
}

Java collection framework doesn't provide any direct utility method to convert ArrayList to String in Java. But Spring framework which is famous for dependency Injection and its IOC container also provides API with common utilities like method to convert Collection to String in Java. You can convert ArrayList to String using Spring Framework's StringUtils class. StringUtils class provide three methods to convert any collection

eg ArrayList to String in Java, as shown below:

public static String collectionToCommaDelimitedString(Collection coll)
public static String collectionToDelimitedString(Collection coll, String delim)
public static String collectionToDelimitedString(Collection coll, String delim, String  prefix, String suffix)

got it....

Well i am not really sure if there is some special way to achieve what you are asking . You would need to iterate over the array . You could use the StringBuilder instead of String for a bit of optimization. I am not really sure how much of a boost you would gain in performance ..

Anyway this is how the code would look ..

StringBuilder sb = new StringBuilder();
for (Object o : list1){
  sb.append(o.toString()+delimiter); // delimiter could be , or \t or || 

 //You could manipulate the string here as required..
 //  enter code here`
}
return sb.toString();

You would then need to split the strings if required. ( if they need to go into seperate fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM