return a sub collection given an original, a to and from index. - Java java.util

Java examples for java.util:Collection Sub Collection

Description

return a sub collection given an original, a to and from index.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection original = java.util.Arrays.asList("asdf", "java2s.com");
        int fromIndex = 42;
        int toIndex = 42;
        System.out.println(getSubCollection(original, fromIndex, toIndex));
    }/*  w ww. jav a  2s  .c o m*/


    public static Collection getSubCollection(Collection original,
            int fromIndex, int toIndex) {
        String methodName = "getSubCollection(Collection original, int fromIndex, int toIndex)";
        ArrayList subCollection = new ArrayList();
        Iterator originalIterator = original.iterator();
        int count = 0;
        while (originalIterator.hasNext()) {
            Object nextObject = originalIterator.next();
            if (count >= fromIndex && count <= toIndex) {
                subCollection.add(nextObject);
            }
            count++;
        }
        return subCollection;
    }
}

Related Tutorials