Home > Blockchain >  Copy SOME values of array IF condition is being met into another array
Copy SOME values of array IF condition is being met into another array

Time:12-05

 int a[] = {1, 6, 3, 4, 5, 8, 7};

 for(int i = 0; i < a.length; i  ){
  
      if (a[i] % 2 == 0) {

            int b = new int[3];

          b[i] = a[i];

          System.out.print(b[i]   " ");
}
}

//I want a new array b, to have the even values of a. How can I make this work?

CodePudding user response:

There are two ways. First way introduce a new counter:

        int a[] = {1, 6, 3, 4, 5, 8, 7};
        int b[] = new int[a.length/2];
        int count = 0;
        for (int i = 0; i < a.length; i  ) {
            if (a[i] % 2 == 0) {
                b[count] = a[i];
                System.out.print(b[count]   " ");
                count  ;
            }
        }

The second way is to use Java Streams:

        int[] ints = Arrays.stream(a).filter(item -> item % 2 == 0).toArray();
        for (int i : ints) {
            System.out.println(i);
        }

The second way can be problematic in performance optimized environments, or if the arrays are really huge, as we need to iterate twice over the items.

See also benchmarking of Java Streams here

If you only need to print the result, you can avoid the iterations via

Arrays.stream(a).filter(item -> item % 2 == 0).forEach(System.out::println);

CodePudding user response:

I think you need to check the ordering of your code.

Each For loop iteration, if your number meets the criteria your creating a new array called b and adding the value, however, on the next iteration, the array no longer exists so another new one is created.

In addition to this, you're also setting the index of b, based on the index of a, however, b's array only has 3 elements, therefore it will fail from index 4 onwards. So you would also need a second index to reference (in the below I've called this 'j', and you would use this to assign values to b's array

Consider declaring b under your declaration of a, then print the result outside of the for loop like so:

int[] a = new int[] {1, 6, 3, 4, 5, 8, 7};
int[] b = new int[3];
int j = 0;

for(int i = 0; i < a.length; i  ) {
    if (a[i] % 2 == 0) {
        b[j] = a[i];
        j  ;
    }
}
//  Output the Values of b here
for(int i = 0; i < b.length; i  ) {
    System.out.print(b[i]   " ");
}

One thing to keep in mind here, that this will work for the values you've provided, however what if the values change and there are more elements in a's array? You'd need to define b with more elements, so using an array with a set length wouldn't be best practise here. Consider using a List instead.

  •  Tags:  
  • java
  • Related