将特定数字从一个数组复制到另一个数组

Copy specific numbers from one array to another

有没有办法将特定数字从一个数组复制到另一个数组?
例如:
我有一个数组 {1, 2, 3, 4, 5}
我想将奇数和偶数复制到单独的数组中。所以,结果应该是
{2, 4}, {1, 3, 5}

试试这个。

public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5};

    int[] even = IntStream.of(array).filter(i -> i % 2 == 0).toArray();
    int[] odd = IntStream.of(array).filter(i -> i % 2 != 0).toArray();

    System.out.println("even = " + Arrays.toString(even));
    System.out.println("odd = " + Arrays.toString(odd));
}

输出:

even = [2, 4]
odd = [1, 3, 5]
int[] ls={1, 2, 3, 4, 5};

List<Integer> odd=new ArrayList<Integer>();
for (int l :ls) {
    if(l%2==1) {
        odd.add(l);
    }
}
System.out.println(odd);

List<Integer> even=new ArrayList<Integer>();
for (int l :ls) {
    if(l%2==0) {
        even.add(l);
    }
}
System.out.println(even);

试试这个

import java.util.*;

class Dragon {
    public static void main(String[] args) {
        int[] list = { 1, 2, 3, 4, 5 };

        List<Integer> oddList = new ArrayList<Integer>();
        List<Integer> evenList = new ArrayList<Integer>();

        for (int l : list) {
            if (l % 2 == 0)
                evenList.add(l);
            else
                oddList.add(l);
        }
        System.out.println("Odd = " + oddList);
        System.out.println("Even = " + evenList);
    }
}

输出

Odd = [1, 3, 5]
Even = [2, 4]