JAVAutil。流动IntStream/LongStream |搜索元素

给定一个整数或长数据类型的元素数组,需要使用中的预定义函数检查该数组中是否存在给定的键 JAVAutil。流动IntStream .爪哇。util。流动IntStream/LongStream类包含函数anyMatch(),该函数有助于检查数组中是否存在特定元素。

null

例如:

Input : arr[] = {1,2,3,4,5,6,7} ,  key = 3
Output : Yes
         3 is present in the array.

Input : arr[] = {1,2,3,4,5,6,7} ,  key = 8
Output : No

这个 流动anyMatch() 方法用于检查流是否包含与给定谓词匹配的任何此类元素。如果流中至少有1个元素与给定的谓词条件匹配,它将返回true,否则它将返回false。 语法:

boolean anyMatch(Predicate< ? super T >  predicate)

下面是一个Java程序,介绍如何将anyMatch()方法同时用于整数流和长整数流。

// Java program to check if an element is present
// in an array using java.util.stream.IntStream
import java.util.stream.IntStream;
import java.util.stream.LongStream;
class CheckElement
{
public static void main (String[] args)
{
// stream of integer
int num[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 };
int key = 3 ; // key to be searched
boolean result = IntStream.of(num).anyMatch(x -> x == key);
if (result)
System.out.println( "Yes" );
else
System.out.println( "No" );
// stream of long
long lnum[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 };
// key to be searched
long lkey = 7 ;
boolean result2 = LongStream.of(lnum).anyMatch(x -> x == lkey);
if (result2)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}


输出:

Yes
Yes

参考 : anyMatch()java文档

本文由 阿卡什·辛格 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享