📜  Java.util.stream.IntStream/LongStream |搜索元素

📅  最后修改于: 2022-05-13 01:54:26.835000             🧑  作者: Mango

Java.util.stream.IntStream/LongStream |搜索元素

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

例子:

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

Stream.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文档