Java将数组拆分为范围

时间:2015-05-23 16:09:39

标签: java arrays

使用Java,我想将一个int数组拆分成一个范围数组。例如,数组

[1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 102, 103]

将返回

[Range(1, 8), Range(100, 103)]

因为它由1到8和100到103

组成

最好是有一个库,但是这种转换的任何方法都可以。

2 个答案:

答案 0 :(得分:2)

Ok James,这是你的工作解决方案:)。

private void executeTestCode(){
    int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 102, 103};      
    Range[] ranges = Arrays.stream(getRanges(arr)).filter(r -> r != null).toArray(Range[]::new);        
    String output = Arrays.stream(ranges)
            .map(Range::toString)
            .reduce("[", (dynamicString, stringedRange) -> (dynamicString + stringedRange + ", "));
    output = output.substring(0, output.length()-2) + "]";
    System.out.println(output);
}

输出:
[范围(1,8),范围(100,103)]

private Range[] getRanges(int[] toBeProcessed){
    Range[] result = new Range[toBeProcessed.length]; //larger array won't be needed
    int startRange = toBeProcessed[0];  
    int ranges = 0;
    for(int a=0; a<toBeProcessed.length; a++){
        try{
            if(toBeProcessed[a] + 1 != toBeProcessed[a+1]){                 
                result[ranges] = new Range(startRange, toBeProcessed[a]);
                startRange = toBeProcessed[a+1];
                ranges++;
            }                   
        }catch(ArrayIndexOutOfBoundsException e){
            result[ranges] = new Range(startRange, toBeProcessed[toBeProcessed.length-1]);
        }
    }
    return result;      
}



CLASS范围:

class Range{
    private int start, end;
    public Range(int st, int en){
        start = st;
        end = en;
    }

    @Override
    public String toString(){
        return "Range(" +start+ ", " +end+ ")";
    }
}

答案 1 :(得分:1)

您可以使用

Arrays.copyOfRange(yourArray, inclusiveStartIndex, exclusiveEndIndex);

它返回新数组。