4

Simply, I have a set of numbers like this.

int targetNumber = 8;

int[] n = new int[4];
n[0] = 2;
n[1] = 4;
n[2] = 8;
n[3] = 16;

Now, I'm trying to return 3 numbers.

For example, since n[2] is equal to the targetNumber, I want to return n[0], n[1], and n[3].

Any ways on how I can do that?

1
  • You can only return one object or primitive. You could, for example, return a smaller array with the values you want, or define an object with related fields then set those fields and return the object. Commented Oct 2, 2016 at 2:03

2 Answers 2

4

You can make use of the interface Stream

Arrays.stream(n)
.filter(value -> value != targetNumber)
.limit(3)/*if you want to print only the first three results*/
.forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I recently started learning about Java streams, and this answer is very helpful for me.
2

You can do it in classic fashion:

for (int i : n) {
    if (i != targetNumber)
        System.out.println(i);
}

output will be n[0], n[1] and n[3]

2
4
16

4 Comments

I thought the question was getting only three numbers :)
@Dev.Joel your answer is valid I think it might be over complicated for OP, I like streams but maybe OP have not enough knowledge of streams yet. any way I give my vote for you as well. I think also he mean 3 remain numbers of 4
It is also possible that the focus of the question is to return 3 items because the array is 4. I understood back 3 items generally equal his response was accepted because it was what he wanted the OP. all right
I agree but I think still the only reason OP did not get it because it is new stuff to him/her to understand any nice chatting with you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.