Kcits970
Kcits970

Reputation: 642

How to return specific values in an array?

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?

Upvotes: 4

Views: 1548

Answers (2)

Maytham Fahmi
Maytham Fahmi

Reputation: 33437

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

Upvotes: 2

Dev. Joel
Dev. Joel

Reputation: 1147

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

Upvotes: 4

Related Questions