java中count的用法_Java Stream count()用法及代码示例

long count()返回流中元素的计数。这是归约的一种特殊情况(归约运算采用一系列输入元素,并通过重复应用组合运算将它们组合成单个汇总结果)。这是终端操作,即可能会遍历流以产生结果或副作用。执行终端操作后,流管线被视为已消耗,无法再使用。

用法:

long count()

注意:计数操作的返回值是流中元素的计数。

示例1:计算数组中的元素数。

// Java code for Stream.count()

// to count the elements in the stream.

import java.util.*;

class GFG {

// Driver code

public static void main(String[] args)

{

// creating a list of Integers

List list = Arrays.asList(0, 2, 4, 6,

8, 10, 12);

// Using count() to count the number

// of elements in the stream and

// storing the result in a variable.

long total = list.stream().count();

// Displaying the number of elements

System.out.println(total);

}

}

输出:

7

示例2:计算列表中不同元素的数量。

// Java code for Stream.count()

// to count the number of distinct

// elements in the stream.

import java.util.*;

class GFG {

// Driver code

public static void main(String[] args)

{

// creating a list of Strings

List list = Arrays.asList("GFG", "Geeks", "for", "Geeks",

"GeeksforGeeks", "GFG");

// Using count() to count the number

// of distinct elements in the stream and

// storing the result in a variable.

long total = list.stream().distinct().count();

// Displaying the number of elements

System.out.println(total);

}

}

输出:

4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值