我的github
posts - 3243,  comments - 42,  views - 158万

1.使用遍历的方式查找某个元素:

public static int findElement(int[] array, int target) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            return i;
        }
    }
    return -1; // 如果未找到目标元素,返回-1表示不存在
}

2.使用二分查找的方式查找有序数组中某个元素:

复制代码
public static int binarySearch(int[] array, int target) {
    int left = 0;
    int right = array.length - 1;
 
    while (left <= right) {
        int mid = left + (right - left) / 2;
 
        if (array[mid] == target) {
            return mid;
        } else if (array[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
 
    return -1; // 如果未找到目标元素,返回-1表示不存在
}
复制代码

3.使用Java 8的Stream API进行查找:

复制代码
public static OptionalInt findElement(int[] array, int target) {
    return Arrays.stream(array)
            .filter(element -> element == target)
            .findFirst();
}
// 使用示例:
OptionalInt result = findElement(array, target);
if (result.isPresent()) {
    int index = result.getAsInt();
    // 对应元素存在,执行相应操作
} else {
    // 对应元素不存在,执行相应操作
}
复制代码

4.若数组已经排序,可以使用Arrays类中的binarySearch方法进行查找:

public static int binarySearch(int[] array, int target) {
    return Arrays.binarySearch(array, target);
}
// 注意:在使用该方法时,需要保证数组已经排序,若数组未排序,结果可能不正确

>>https://www.cnblogs.com/2008nmj/p/17648174.html(ArrayList进阶查找)

https://cloud.tencent.com/developer/article/2073980(流与多维数组)

flatMap:使用flatMap操作符将多维数组展平为单维数组后再进行查询:

复制代码
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public class Main {
    public static void main(String[] args) {
        Integer[][] multiDimensionalArray = {{1, 2}, {3, 4}};
        int targetValue = 3;
        
        List<Integer> flattenedList = IntStream.range(0, multiDimensionalArray.length)
                                               .mapToObj(i -> multiDimensionalArray[i])
                                               .flatMap(Arrays::stream)
                                               .collect(Collectors.toList());
        
        Optional<Integer> foundValue = flattenedList.stream()
                                                   .filter(value -> value == targetValue)
                                                   .findFirst();
        
        System.out.println(foundValue.orElse(-1));
    }
}
复制代码

java多维数组获取某一维度的数据

posted on   XiaoNiuFeiTian  阅读(1025)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2022-01-04 ArcGIS 10.2.2 补丁
2022-01-04 ModelBuilder
2022-01-04 ArcGIS Server如何发布gp服务2
2022-01-04 ArcGIS Server动态图层的数据源
2022-01-04 ArcGIS Server添加数据源之后无法启动。。
2022-01-04 Internet Explorer安全设置-解决ArcGIS Server无法加载解析.sde文件
2021-01-04 ArcMap如何只显示部分要素
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示