What is the best and optimal solution to iterate thought list of array of strings and get its value out?
I have list of array of strings, List <String []>
, what is the best optimal approach to get contents of this list of array of strings?
public List<String []> readFromString (String data){
StringReader stringReader = new StringReader(data);
CVSReader reader = new CVSReader(stringReader);
return reader.readAll()
}
In above example, I want to see the actual contain of reader开发者_StackOverflow社区.readAll(), any suggestions as to what is the optimal way to get that information out?
I don't think there's any avoiding looping through the entire structure. Even if you call .toString(), which may well give what you want, you're still going to incur the cost of looping over the entire data structure:
String results = readFromString(data);
StringBuilder output = new StringBuilder();
for(String[] sArray : results) {
for(String s : sArray) {
output.append(s);
}
}
System.out.println(output);
(Note: insert formatting characters as required - you might want to put a comma after each string, and a \n after each list completes, to make the output more readable.)
By wanting to see the content and "get information out", if you mean that you want to send it to standard out, or your log file, to see a full dump of the data, you can use the List toString (i.e. System.out.println(reader.readAll());
). It prints all values. The following unit test confirms it:
public void testListOfArraysToStringPrintsAllValues(){
String[] array1 = ["array1.1", "array1.2"];
String[] array2 = ["array2.1", "array2.2"];
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(array1);
listOfArrays.add(array2);
assertEquals("[[array1.1, array1.2], [array2.1, array2.2]]", listOfArrays.toString());
}
Are you looking for something like this?
for(String[] sArray : new CVSReader(new StringReader(data)).readAll())
{
for(String s : sArray)
{
System.out.prinntln(s);
}
System.out.prinntln("*********");
}
I can be wrong but my suggetions are:
- To separte the lines:
String[] lines = data.split("\n");
- To get a java.util.List
java.util.Arrays.asList(lines)
- To separate each line:
String[] fields = line.split(",");
where line
will be one of the String[] lines
element.
精彩评论