get element in collection by index - Java java.util

Java examples for java.util:Collection Element

Description

get element in collection by index

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        Collection coll = java.util.Arrays.asList("asdf", "java2s.com");
        int index = 42;
        System.out.println(get(coll, index));
    }/*from  w w w  .  jav  a2  s .  c o m*/

    public static <T> T get(final Collection<T> coll, final int index) {
        final Iterator<T> it = coll.iterator();
        int i = 0;
        T ret = null;
        while (it.hasNext()) {
            ret = it.next();
            if (i >= index)
                break;
            i++;
        }
        return ret;
    }
}

Related Tutorials