How to create a sub array from another array in Java?

前端 未结 9 516
醉话见心
醉话见心 2020-11-29 16:02

How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int          


        
9条回答
  •  借酒劲吻你
    2020-11-29 16:50

    JDK >= 1.8

    I agree with all the answers above. There is also a nice way with Java 8 Streams:

    int[] subArr = IntStream.range(startInclusive, endExclusive)
                            .map(i -> src[i])
                            .toArray();
    

    The benefit about this is, it can be useful for many different types of "src" array and helps to improve writing pipeline operations on the stream.

    Not particular about this question, but for example, if the source array was double[] and we wanted to take average() of the sub-array:

    double avg = IntStream.range(startInclusive, endExclusive)
                        .mapToDouble(index -> src[index])
                        .average()
                        .getAsDouble();
    

提交回复
热议问题