如何将数组中的特定元素放入另一个数组中

时间:2016-12-22 17:10:14

标签: java arrays

如何将数组中的元素放入Java中的另一个数组?例如,我有一个数组{41,-2,1,2,-88,55,-4},我想只复制一个单独数组中的负数?

我试过了:

title

3 个答案:

答案 0 :(得分:1)

试试这个:

public static void main(final String[] args) {
    int[] array = {1, 2, -1, 2};
    List<Integer> arlNumber = new ArrayList<Integer>();
    for (final int number : array) {
        if (number < 0) {
            arlNumber.add(number);
        }
    }

    Integer[] arrayResult = arlNumber.toArray(
            new Integer[arlNumber.size()]);
}

答案 1 :(得分:1)

您可以采用的一种方法是在使用Java 8平台时利用lambda过滤器表达式。这将减少代码中的锅炉板数量。例如:

    List<Integer> source = Arrays.asList(41, -2, 1, 2, -88, 55, -4);

    List<Integer> negatives = source.stream().filter(x -> x < 0).collect(Collectors.toList());

    System.out.println(source);
    System.out.println(negatives);
  • [41,-2,1,2,-88,55,-4]来源
  • [ - 2,-88,-4]否定

由于源数组是一个集合(List),因此stream()方法在该数组中提供了一系列整数。对于流中的每个整数,应用过滤器,并将与谓词(x <0)匹配的过滤器提供给收集器,收集器组合那些匹配整数的列表。

这个tutorial提供了有关Java 8 Lambda的更多细节。

答案 2 :(得分:0)

public class arraycheck {





     public static void main(String args[]) {
            int a[] = { 41, -2, 1, 2, -88, 55, -4 };
            int b[] = new int[a.length];

            for (int i = 0; i < a.length; i++) {

                if(a[i] < 0)
                {

                    System.out.println(a[i]);
                    b[i] = a[i];;
                }

            }
        }