简体   繁体   English

使用IntStream检查2D数组中的数组

[英]checking for an array within a 2D array using IntStream

I'm looking to check if a set of coordinates ( coor ) exists within an array of coordinates ( coorArray ). 我期待,以检查是否一组坐标( coor )坐标的数组(中存在coorArray )。 I've seen in other posts how to concatenate the 2D array so that it can be searched for in an IntStream for a lone int but I'm not sure how to translate that towards my problem. 我在其他帖子中看到如何连接2D数组,以便可以在IntStream搜索单独的int但我不确定如何将其转换为我的问题。 Thank you for the help! 感谢您的帮助!

example arrays: 示例数组:

int[][] coorArray = {{1,2},{2,2},{3,0}};
int[] coor = {1,2};

Yoy can use stream().anyMatch() to perform this check: Yoy可以使用stream().anyMatch()来执行此检查:

int[][] coorArray = {{1,2},{2,2},{3,0}};
int[] coor = {1,2};
boolean exist = Arrays.stream(coorArray).anyMatch(e -> Arrays.equals(e, coor));
System.out.println("exist = " + exist);  

Outputs: 输出:

exist = true


Otherwise, when coordinates is not exists in input array: 否则,当输入数组中不存在坐标时:

int[][] coorArray = {{4,2},{2,2},{3,0}};
int[] coor = {1,2};
boolean exist = Arrays.stream(coorArray).anyMatch(e -> Arrays.equals(e, coor));
System.out.println("exist = " + exist);

Outputs: 输出:

exist = false

Here is another example without lambda expressions if you like ;). 这是另一个没有lambda表达式的例子,如果你喜欢;)。 Consisting of a simple for each and the check per coordinate. 每个坐标组成一个简单的每个坐标。

public static boolean exists(int[][] coords, int[] coord){
    for(int[] c : coords){
        if(c[0] == coord[0] && c[1] == coord[1]) {
            return true;
        }
    }
    return false;
}

I'm not sure if there is something else available in the API but that should serve the requirement. 我不确定API中是否还有其他可用的东西但是应该满足要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM