Java Collection First getFirstN(Collection objects, int n)

Here you can find the source of getFirstN(Collection objects, int n)

Description

get First N

License

Open Source License

Return

A new list with only n elements.

Declaration

public static <E> List<E> getFirstN(Collection<E> objects, int n) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

public class Main {
    /**/*from   w  ww.ja  v  a  2 s.c om*/
     * @return A new list with only n elements.
     */
    public static <E> List<E> getFirstN(Collection<E> objects, int n) {
        if (objects == null)
            return null;

        List<E> newlist = new ArrayList<E>();
        int i = 0;
        for (E item : objects) {
            if (i < n)
                newlist.add(item);
            else
                break;
            i++;
        }
        return newlist;
    }
}

Related

  1. getFirstElementOrNull(Collection coll)
  2. getFirstItem(Collection c)
  3. getFirstItem(Collection collection)
  4. getFirstItem(Collection c)
  5. getFirstItemInCollection(Collection collection)
  6. getFirstNonNull(Collection c)
  7. getFirstNotNullValue(final Collection collection)
  8. getFirstOrNull(final Collection collection)
  9. getFirstSortedItem( Collection items, T defaultValue)