2017-03-09 91 views
-1

在我有這樣的代碼Stream.filter()離開零點陣列

int[] array = {1, -1, 2, 3, -4}; 

Integer[] out = Arrays 
    .stream(array) 
    .filter(elem -> elem >= 0) // remove negatives 
    .boxed() 
    .collect(Collectors.toList()) 
    .toArray(new Integer[array.length]); 

但是濾波操作離開陣列null S IN的負性元件。爲什麼它不刪除它們?

+0

好像你已經混'int'用'Integer'大多 - > http://stackoverflow.com/questions/42685825/arraystoreexception-thrown-when-converting-hashset-to-array – nullpointer

回答

5

您的out陣列長度與array陣列相同。

做任何這樣的:

int[] out = Arrays 
     .stream(array) 
     .filter(elem -> elem >= 0) // remove negatives 
     .toArray(); 

或做到這一點:

Integer[] out = Arrays 
     .stream(array) 
     .filter(elem -> elem >= 0) // remove negatives 
     .boxed() 
     .toArray(Integer[]::new); 
0

按照下面的代碼

int test[] = new int[] { 15, -40, -35, 45, -15 }; 
    // here we can take the test array in to stream and filter with condition (>=0). 
    int[] positives = Arrays.stream(test).filter(x -> x >= 0).toArray(); 

    System.out.println("Here is the positive array elements"); 

    for (int i : positives) { 
     System.out.print(i + "\t"); 
    }