我有很大的字符串ArrayList。列表中的每个String元素也非常大。我想算一下这个词的次数""出现在列表的每个元素中。我当前的代码只遍历索引1.如何计算数组的所有元素?
from pydocumentdb import document_client
print('START----------------------')
uri = 'https://10.107.0.111:8081'
key = 'MY_KEY'
client = document_client.DocumentClient(uri, {'masterKey': key})
db_id = 'MY_ID'
db_query = "select * from r where r.id = '{0}'".format(db_id)
db = list(client.QueryDatabases(db_query))[0]
答案 0 :(得分:1)
不要调用subList
并在迭代整个列表后返回:
public static int counter(List<String> comments) {
int count = 0;
String word = "the";
for (String comment : comments) {
String a[] = comment.split(" ");
for (int j = 0; j < a.length; j++) {
if (word.equals(a[j])) {
count++;
}
}
System.out.println(comment);
}
System.out.println("sefsfsfseesfeseeeeeeeeeeeeeeeeeeeeeee");
return count;
}
答案 1 :(得分:1)
您的方法类型不正确,而应该是Map<String, Long>
如果您使用的是Java 8,则可以创建每个单词及其频率的映射,如下所示:
Map<String, Long> result = comments.stream()
.flatMap(comment -> Stream.of(comment.split("\\s+")))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
然后,如果您想要显示多少the
,可以使用:
String word = "the";
Long count = result.get(word);
或者只是:
Long count = comments.stream()
.flatMap(comment -> Stream.of(comment.split("\\s+")))
.filter(s -> s.equals(word))
.count();