-1

Problem: I have a String 100, 200, boxes. I want to convert this String into an object, let's say TreeMap<String, List>, with 100, 200 as a List of values and boxes as a String that is a key. The result should look like [100, 200]: "boxes".

Later I would like to access the values: my_map.get("boxes")[0] or my_map.get("boxes")[1] for example.

My Solution: Let's say I have a file with 3 columns, I read the data, split it and iterate over each line splitting the line on the go. I assume I have [100, 200, "boxes"]. Now in python I could simply access the elements I need by providing a range of indexes like [0:1].

How to do the same thing in Java?

for (String line : mydata.split("\n|\r\n")) {

            String[] sl = line.split(" |\t");
            String[] my_two_elements = sl[0:1]; <-- No way!

        } 
minerals
  • 6,090
  • 17
  • 62
  • 107

1 Answers1

1

You are looking for Arrays.copyOfRange(array,from,to);

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

The resulting array is of exactly the same class as the original array.

Always refer to the source for implementation details and profile your code for performance.

3035    public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3036        int newLength = to - from;
3037        if (newLength < 0)
3038            throw new IllegalArgumentException(from + " > " + to);
3039        T[] copy = ((Object)newType == (Object)Object[].class)
3040            ? (T[]) new Object[newLength]
3041            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3042        System.arraycopy(original, from, copy, 0,
3043                         Math.min(original.length - from, newLength));
3044        return copy;
3045    }