How to return certain values ​​to an array? - Java

I just 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 am trying to return 3 numbers.

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

Any ways how can I do this?

+4
source share
2 answers

You can do it in a classic way:

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

will n[0], n[1]andn[3]

2
4
16
+2
source

You can use the Stream interface

Arrays.stream(n)
.filter(value -> value != targetNumber)
.limit(3)/*if you want to print only the first three results*/
.forEach(System.out::println);
+3
source

Source: https://habr.com/ru/post/1656486/


All Articles