有沒有一種簡單的方法可以快速過濾一組元素以僅輸出鄰居?假設我有一個元素數組?,F在我想找到特定元素的鄰居。我編寫的代碼有效,但看起來很丑,我想找到一個更易于閱讀的解決方案。我的代碼: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 回答
海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
這是一個很好的簡短解決方案:
if(index > 0) System.out.println(myArray[index-1])
if(index < array.length-1) System.out.println(myArray[index+1])
一只甜甜圈
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
提交
取消
