有没有一种简单的方法可以快速过滤一组元素以仅输出邻居?假设我有一个元素数组。现在我想找到特定元素的邻居。我编写的代码有效,但看起来很丑,我想找到一个更易于阅读的解决方案。我的代码:int[] myArray = {6, 8, 9, 12, 30};// index of element where I want to find the neighbors ofint index = 1;if(index == 0){ //first element so only add the right neighbor System.out.println(myArray[1]);} else if(index == myArray.length -1){ //last element so only add left neighbor System.out.println(myArray[index-1]);} else{ //middle element so add both neighbors System.out.println(myArray[index-1]); System.out.println(myArray[index+1]);}
2 回答
![?](http://img1.sycdn.imooc.com/533e4d00000171e602000200-100-100.jpg)
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
这是一个很好的简短解决方案:
if(index > 0) System.out.println(myArray[index-1])
if(index < array.length-1) System.out.println(myArray[index+1])
![?](http://img1.sycdn.imooc.com/56fb3e3d0001a10301000100-100-100.jpg)
一只甜甜圈
TA贡献1836条经验 获得超5个赞
实际上,使用 Java 8,您可以通过非常简单的 lambda 解决方案来使用它:
final int[] numbs = { 1, 3, 5, 7 };
int index = 2;
IntStream.rangeClosed(index - 1, index + 1)
.filter(idx -> idx != index && idx >= 0 && idx < numbs.length)
.forEach(idx -> System.out.println(numbs[idx]));
但是,请创建一个接收数组和索引的方法,以便重用代码。
添加回答
举报
0/150
提交
取消