在groovy中计算数组列表中的非空字符串的数量

x33g5p2x  于2022-10-25 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(1147)

在本例中,我们将演示如何使用groovy对集合中的字符串进行计数。我们将一个闭包传递给count方法,在这里我们将检查字符串是否为null,长度是否大于0。

计数集合中的非空字符串

  1. @Test
  2. void count_non_empty_strings_in_arraylist() {
  3. def occurrences = [
  4. "packers",
  5. null,
  6. "",
  7. "fans",
  8. null,
  9. "Go pack Go!"
  10. ].count ({ it -> it != null && it.length() > 0 })
  11. assert 3, occurrences
  12. }

Objects utility方法是在java7中引入的,而nonNull是在java8中添加的。此示例将使用变体检查字符串是否为null。

  1. @Test
  2. void count_non_empty_strings_in_arraylist() {
  3. def occurrences = [
  4. "packers",
  5. null,
  6. "",
  7. "fans",
  8. null,
  9. "Go pack Go!"
  10. ].count ({ it -> Objects.nonNull(it) && it.length() > 0 })
  11. assert 3, occurrences
  12. }

相关文章