如果我有一个List<List<String>>Java数据,我可以通过代码得到第一个列表的长度:
int lengthData = data.get(0).size();
Run Code Online (Sandbox Code Playgroud)
但是如何在不遍历列表列表的情况下获取结构中的列表数量?
也许我有点不清楚.我有结构:
List<List<String>> data
Run Code Online (Sandbox Code Playgroud)
我明白了:
int i = data.size();
Run Code Online (Sandbox Code Playgroud)
将等于1,因为它是根列表.所以我想知道的是有多少个子列表.遍历这样的结构:
for (List<String> l : data) {
total ++;
}
Run Code Online (Sandbox Code Playgroud)
只给我一个我觉得奇怪的结果.
我有以下形式的数据:
List 1 ==> 1, 2, 3, 4
List 2 ==> 3, 8. 9, 1
Run Code Online (Sandbox Code Playgroud)
等等这些是根列表的子列表.
Jon*_*eet 66
只是用
int listCount = data.size();
Run Code Online (Sandbox Code Playgroud)
这告诉你有多少列表(假设没有列表为空).如果你想知道有多少字符串,你需要迭代:
int total = 0;
for (List<String> sublist : data) {
// TODO: Null checking
total += sublist.size();
}
// total is now the total number of strings
Run Code Online (Sandbox Code Playgroud)
小智 6
爪哇8
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<List<String>> stringListList = new ArrayList<>();
stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));
int count=stringListList.stream().mapToInt(i -> i.size()).sum();
System.out.println("stringListList count: "+count);
}
}
Run Code Online (Sandbox Code Playgroud)