如何获取Java列表的长度? [英] How do I get length of list of lists in Java?

查看:867
本文介绍了如何获取Java列表的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Java中有列表< List< String>> 数据,我可以通过代码获取第一个列表的长度:

If I have a List<List<String>> data in Java, I can get the length of the first list via code:

int lengthData = data.get(0).size();

但如何在不遍历列表列表的情况下获取结构中的列表数量以查找?

But how do I get the number of lists in the structure without traversing the list of lists to find out?

也许我有点不清楚。我有结构:

Maybe I've been a bit unclear. I have the structure:

List<List<String>> data 

我看到:

int i = data.size();

等于1,因为它是根列表。所以我想知道的是有多少个子列表。遍历这样的结构:

Will equal 1 because it is the root list. So what I want to know is how many sublists there are. Traversal of the structure like this:

for (List<String> l : data) {                     
     total ++;                
}

只给我一个1的结果,我觉得很奇怪。

Only gives me a result of 1 which I find odd.

我有以下表格的数据:

List 1 ==> 1, 2, 3, 4
List 2 ==> 3, 8. 9, 1

等等这些是根列表的子列表。

And so on where these are sublists of the root list.

推荐答案

只需使用

int listCount = data.size();

这可以告诉你有多少列表(假设没有为空) 。如果你想知道有多少字符串,你需要迭代:

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

这篇关于如何获取Java列表的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆