Java Stream count()方法示例

x33g5p2x  于2022-09-24 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(295)

本文将介绍 Stream.count() 方法示例。 count() 方法返回此流中元素的Count。 count() 方法是流缩减的特例。
从 Java 文档中找到 count() 方法声明。

long count()

返回:
count() 返回此流中元素的Count。

count() 是流终端操作。流操作分为中间操作和终端操作,组合起来形成流管道。中间操作是惰性操作,例如 filter() 方法,它们实际上不执行任何过滤,而是创建一个新流,并且在遍历初始流时,它们仅包含与给定谓词匹配的那些元素。只有在执行 count() 等终端操作时,才会对流水线进行遍历。

示例 1:查找数字列表。

List<Integer> numList = Arrays.asList(42, 44, 43, 41);

count() 方法返回流中元素的Count。

long c = numList.stream().count();

c 的值为 4。
现在让我们对流使用 filter 方法,然后计算元素。

long c = numList.stream().filter(e -> e % 2 == 0).count();

c 的值为 2。

count() 是流缩减的特例。在不使用 count() 方法的情况下查找代码以获取Count。

long c = numList.stream().mapToLong(e -> 1L).sum();

c 的值为 4。

示例 2:查找名称列表。

List<String> strList = Arrays.asList("Mohit", "Nilesh", "Mahesh");

让我们在列表的流上使用 count()

long c = strList.stream().count();

c 的值为 3。
现在在字符串流上使用 filter 并计算它。

long c = strList.stream().filter(e -> e.startsWith("M")).count();

c 的值为 2。

我们知道 count() 是流缩减的特例。让我们在不使用 count() 方法的情况下找到Count。

long c = strList.stream().filter(e -> e.startsWith("M")).mapToLong(e -> 1L).sum();

c 的值为 2。

Example-3:在这个例子中,我们有一个对象列表。我们将根据给定的条件过滤列表流,然后计算元素。
CountDemo.java

package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class CountDemo {
  public static void main(String[] args) {
	List<User> users = Arrays.asList(
		new User("Vikas", 30),
		new User("Krishna", 29),
		new User("Virat", 30),
		new User("Mahesh", 30)
	);
	long c1 = users.stream().filter(u -> u.getUserName().startsWith("V")).count();
        System.out.println(c1); //Output: 2
    
	long c2 = users.stream().filter(u -> u.getAge() == 30).count();
        System.out.println(c2); //Output: 3
  }
}
class User {
  private String userName;
  private int age;
  public User(String userName, int age) {
	this.userName = userName;
	this.age = age;
  }
  //Sets and Gets
}

输出

2
3

相关文章

微信公众号

最新文章

更多