Java 8 Filter Array Using Lambda

前端 未结 2 1691
你的背包
你的背包 2020-12-03 00:42

I have a double[] and I want to filter out (create a new array without) negative values in one line without adding for loops. Is this possible usin

相关标签:
2条回答
  • 2020-12-03 01:00

    even simpler, adding up to String[],

    use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

    import org.apache.commons.lang3.StringUtils;

        String test = "a\nb\n\nc\n";
        String[] lines = test.split("\\n", -1);
    
    
        String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
        System.out.println(Arrays.toString(lines));
        System.out.println(Arrays.toString(result));
    

    and output: [a, b, , c, ] [a, b, c]

    0 讨论(0)
  • 2020-12-03 01:03

    Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

    double[] d = {8, 7, -6, 5, -4};
    d = Arrays.stream(d).filter(x -> x > 0).toArray();
    //d => [8, 7, 5]
    

    If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

    String[] a = { "s", "", "1", "", "" };
    a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
    
    0 讨论(0)
提交回复
热议问题