There are times when the value returned from DAO is in the List and I want to concatenate the values and retrieve them. This time I will leave a memorandum about how to do it in such a case.
Note) If you use the second method as it is, a warning will appear at compile time, so correct it. Please use it.
For the code itself, refer to the link below. [Java] Make the string array a comma-separated string
Issue the following command at the command prompt
cd ListTest.Directory with java
javac ListTest.java
java ListTest
<--- Execution result ----------------------------> Type of first list class java.lang.String The contents of the first list. Comma connection: a, b Second list type class java.lang.String The contents of the second list. Comma connection: c, d <--------------------------------------->
ListTest.java
import java.util.*;
public class ListTest{
/*
*A program that tests how to write a List
*reference
* http://d.hatena.ne.jp/mtoyoshi/20080717/1216299220
*
* @Disable compile warnings in SuppressWarnings
*/
@SuppressWarnings("unchecked")
public static void main(String[] args){
/*The first one
*
*/
List<String> lst = new ArrayList<String>();
lst.add("a");
lst.add("b");
StringBuilder builder = new StringBuilder();
//Type confirmation
System.out.println("Type of first list" + lst.get(0).getClass());
for(String str : lst) {
builder.append(str).append(",");
}
String result = builder.substring(0, builder.length() - 1);
System.out.println("The contents of the first list. Comma connection:" + result);
/*Second
* List<String> lst2 = new ArrayList<String>();Otherwise you will get a compile-time warning
*/
List lst2 = new ArrayList();
lst2.add("c");
lst2.add("d");
StringBuilder builder2 = new StringBuilder();
//Type confirmation
System.out.println("Second list type" + lst2.get(0).getClass());
for (int i = 0; i < lst2.size(); i++) {
String str2 = (String)lst2.get(i);
builder2.append(str2).append(",");
}
String result2 = builder2.substring(0, builder2.length() - 1);
System.out.println("The contents of the second list. Comma connection:" + result2);
}
}
Recommended Posts