Learner
Learner

Reputation: 119

Java 8 Loop : stuck with 2nd for loop initialize variable

//I am looking for loop using streams as follows:

int inputArray[] = {4, 6, 5, -10, 8, 1, 2};

    for (int i : inputArray)
            {
                for (int j = i+1; j < inputArray.length; j++)
                {
                    if(inputArray[i]+inputArray[j] == inputNumber)}}

// Tried something like but its not working

IntStream intStream1 =  Arrays.stream(inputArray);

    intStream1.forEach(i -> {
            IntStream.range(i+1,... ).forEach(j -> {

            });
        });

Upvotes: 1

Views: 266

Answers (2)

Serge
Serge

Reputation: 12344

in your expression you iterate through the values of the array, so for

for (int i: inputArray)

values of i will be: 4, 6, 5, -10, 8, 1, 2 sequentially.

Judging by the style of your code, you need

for (int i = 0; i < inputArray.length; i++) 

or similar.

Same story with streams. If you create a primitive stream out of an array of integers, foreach would iterate over its values, not indexes. So, you would need to account for indexes yourself. Here is a possible implementation.

private static int i = 0, j= 0;
IntStream iStream = Arrays.stream(inputArray);

iStream.forEachOrdered(ival -> {
    j = i+1;
    if (j < inputArray.length) {
        IntStream jStream = Arrays.stream(inputArray, j, inputArray.length);      
        jStream.forEachOrdered(jval -> {
            System.out.println(i + "+" + j + ": " + (ival  + jval));
            j++;
        });
    }
    i++;
});

I believe that the above would explain the main idea with streams.

you can also use IntStram.range() to iterate across indexes themselves, or use other possible streaming solutions. Please see other answers in this thread as well.

Upvotes: 2

Ian Mc
Ian Mc

Reputation: 5829

Here is the streams answer you are asking for (finding out if any two numbers in an array sum to a given value)

int inputArray[] = {4, 6, 5, -10, 8, 1, 2};
int inputNumber = -8;

IntStream.range(0, inputArray.length-1).forEach(i -> IntStream.range(i+1, inputArray.length)
    .forEach(j -> {
        if (inputArray[i]+inputArray[j] == inputNumber) 
            System.out.println("Found "+inputNumber+"; a["+i+"]="+inputArray[i]+" a["+j+"]="+inputArray[j]);
        }));;

Which produces the result:

Found -8; a[3]=-10 a[6]=2

Upvotes: 1

Related Questions