Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class Main { public static <O> List<O> head(Collection<O> c, int num) { return extract(c != null ? c.iterator() : null, num); } @SuppressWarnings("unchecked") protected static <O> List<O> extract(Iterator<?> iter, int num) { if (iter == null) { return null; } List<O> list = new ArrayList<O>(); while (iter.hasNext() && (num == -1 || list.size() < num)) { O item = (O) iter.next(); list.add(item); } return list; } }