take n elements from a List and return a List - Java java.util

Java examples for java.util:List Element

Description

take n elements from a List and return a List

Demo Code


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

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        int n = 42;
        System.out.println(take(list, n));
    }// ww  w  . ja  va  2 s  .co  m

    public static <A> List<A> take(List<A> list, int n) {
        List<A> result = new ArrayList<A>();
        for (int j = 0; j < Math.min(n, list.size()); ++j)
            result.add(list.get(j));
        return result;
    }
}

Related Tutorials