Filtering arrays for neighbors Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?PHP: Delete an element from an arrayHow do I determine whether an array contains a particular value in Java?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?

"Seemed to had" is it correct?

Why is black pepper both grey and black?

Antler Helmet: Can it work?

How much radiation do nuclear physics experiments expose researchers to nowadays?

How do I mention the quality of my school without bragging

What is the musical term for a note that continously plays through a melody?

What are the motives behind Cersei's orders given to Bronn?

If 'B is more likely given A', then 'A is more likely given B'

Is 1 ppb equal to 1 μg/kg?

Why are there no cargo aircraft with "flying wing" design?

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

What does '1 unit of lemon juice' mean in a grandma's drink recipe?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Can a non-EU citizen traveling with me come with me through the EU passport line?

Is there a service that would inform me whenever a new direct route is scheduled from a given airport?

I am not a queen, who am I?

Should I call the interviewer directly, if HR aren't responding?

What is this single-engine low-wing propeller plane?

Disable hyphenation for an entire paragraph

List *all* the tuples!

How does a Death Domain cleric's Touch of Death feature work with Touch-range spells delivered by familiars?

What LEGO pieces have "real-world" functionality?

The logistics of corpse disposal

Why aren't air breathing engines used as small first stages



Filtering arrays for neighbors



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?PHP: Delete an element from an arrayHow do I determine whether an array contains a particular value in Java?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Is there an easy way to filter an array of elements quickly to only output the neighbors?



Say I have an array of elements. Now I want to find the neighbors of a specific element.



The code I made works but looks quite ugly and I'd like to find an easier-to-read solution.



My code:



int[] myArray = 6, 8, 9, 12, 30;
// index of element where I want to find the neighbors of
int 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]);










share|improve this question




























    0















    Is there an easy way to filter an array of elements quickly to only output the neighbors?



    Say I have an array of elements. Now I want to find the neighbors of a specific element.



    The code I made works but looks quite ugly and I'd like to find an easier-to-read solution.



    My code:



    int[] myArray = 6, 8, 9, 12, 30;
    // index of element where I want to find the neighbors of
    int 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]);










    share|improve this question
























      0












      0








      0








      Is there an easy way to filter an array of elements quickly to only output the neighbors?



      Say I have an array of elements. Now I want to find the neighbors of a specific element.



      The code I made works but looks quite ugly and I'd like to find an easier-to-read solution.



      My code:



      int[] myArray = 6, 8, 9, 12, 30;
      // index of element where I want to find the neighbors of
      int 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]);










      share|improve this question














      Is there an easy way to filter an array of elements quickly to only output the neighbors?



      Say I have an array of elements. Now I want to find the neighbors of a specific element.



      The code I made works but looks quite ugly and I'd like to find an easier-to-read solution.



      My code:



      int[] myArray = 6, 8, 9, 12, 30;
      // index of element where I want to find the neighbors of
      int 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]);







      java arrays nearest-neighbor






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 16:31









      solutionM4stersolutionM4ster

      135




      135






















          2 Answers
          2






          active

          oldest

          votes


















          2














          Here is a good and short solution:



          if(index > 0) System.out.println(myArray[index-1])
          if(index < array.length-1) System.out.println(myArray[index+1])





          share|improve this answer
































            0














            Actually, using Java 8 you can use this by quite simple lambda solution:



            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]));


            But please, create a method that receives your array and index in order to reuse the code.






            share|improve this answer

























            • I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

              – Anton Sorokin
              Mar 8 at 16:47







            • 1





              no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

              – Sharon Ben Asher
              Mar 8 at 16:49












            • And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

              – Rhuan Karlus
              Mar 8 at 17:42












            • @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

              – Anton Sorokin
              Mar 9 at 5:16











            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067259%2ffiltering-arrays-for-neighbors%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Here is a good and short solution:



            if(index > 0) System.out.println(myArray[index-1])
            if(index < array.length-1) System.out.println(myArray[index+1])





            share|improve this answer





























              2














              Here is a good and short solution:



              if(index > 0) System.out.println(myArray[index-1])
              if(index < array.length-1) System.out.println(myArray[index+1])





              share|improve this answer



























                2












                2








                2







                Here is a good and short solution:



                if(index > 0) System.out.println(myArray[index-1])
                if(index < array.length-1) System.out.println(myArray[index+1])





                share|improve this answer















                Here is a good and short solution:



                if(index > 0) System.out.println(myArray[index-1])
                if(index < array.length-1) System.out.println(myArray[index+1])






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 8 at 16:48

























                answered Mar 8 at 16:37









                Anton SorokinAnton Sorokin

                215314




                215314























                    0














                    Actually, using Java 8 you can use this by quite simple lambda solution:



                    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]));


                    But please, create a method that receives your array and index in order to reuse the code.






                    share|improve this answer

























                    • I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                      – Anton Sorokin
                      Mar 8 at 16:47







                    • 1





                      no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                      – Sharon Ben Asher
                      Mar 8 at 16:49












                    • And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                      – Rhuan Karlus
                      Mar 8 at 17:42












                    • @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                      – Anton Sorokin
                      Mar 9 at 5:16















                    0














                    Actually, using Java 8 you can use this by quite simple lambda solution:



                    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]));


                    But please, create a method that receives your array and index in order to reuse the code.






                    share|improve this answer

























                    • I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                      – Anton Sorokin
                      Mar 8 at 16:47







                    • 1





                      no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                      – Sharon Ben Asher
                      Mar 8 at 16:49












                    • And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                      – Rhuan Karlus
                      Mar 8 at 17:42












                    • @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                      – Anton Sorokin
                      Mar 9 at 5:16













                    0












                    0








                    0







                    Actually, using Java 8 you can use this by quite simple lambda solution:



                    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]));


                    But please, create a method that receives your array and index in order to reuse the code.






                    share|improve this answer















                    Actually, using Java 8 you can use this by quite simple lambda solution:



                    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]));


                    But please, create a method that receives your array and index in order to reuse the code.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 17:40

























                    answered Mar 8 at 16:42









                    Rhuan KarlusRhuan Karlus

                    7151024




                    7151024












                    • I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                      – Anton Sorokin
                      Mar 8 at 16:47







                    • 1





                      no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                      – Sharon Ben Asher
                      Mar 8 at 16:49












                    • And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                      – Rhuan Karlus
                      Mar 8 at 17:42












                    • @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                      – Anton Sorokin
                      Mar 9 at 5:16

















                    • I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                      – Anton Sorokin
                      Mar 8 at 16:47







                    • 1





                      no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                      – Sharon Ben Asher
                      Mar 8 at 16:49












                    • And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                      – Rhuan Karlus
                      Mar 8 at 17:42












                    • @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                      – Anton Sorokin
                      Mar 9 at 5:16
















                    I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                    – Anton Sorokin
                    Mar 8 at 16:47






                    I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.

                    – Anton Sorokin
                    Mar 8 at 16:47





                    1




                    1





                    no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                    – Sharon Ben Asher
                    Mar 8 at 16:49






                    no need to stream the entire range of the array. you can stream just the neighbors IntStream.rangeClosed(index-1, index+1) and filter idx != index && idx >= 0 && idx < numbs.length

                    – Sharon Ben Asher
                    Mar 8 at 16:49














                    And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                    – Rhuan Karlus
                    Mar 8 at 17:42






                    And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.

                    – Rhuan Karlus
                    Mar 8 at 17:42














                    @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                    – Anton Sorokin
                    Mar 9 at 5:16





                    @RhuanKarlus My message doesnt mean that I dont know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

                    – Anton Sorokin
                    Mar 9 at 5:16

















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55067259%2ffiltering-arrays-for-neighbors%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    1928 у кіно

                    Захаров Федір Захарович

                    Ель Греко