Takes up to n items from the head of a list, and returns them in another list. - Java java.util

Java examples for java.util:List Operation

Description

Takes up to n items from the head of a list, and returns them in another list.

Demo Code


//package com.java2s;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        int num = 42;
        System.out.println(topN(list, num));
    }/* ww w.j a  v  a2 s . c om*/

    /**
     * Takes up to n items from the head of a list, and returns them in another list. If the input list has less items,
     * then they will all be returned.
     *
     * @param  list The list to take from.
     * @param  num  The number of elements to take.
     * @param  <T>  The type of the list elements.
     *
     * @return A list with up to n items from the input list.
     */
    public static <T> List<T> topN(List<T> list, int num) {
        List<T> exemplars = new LinkedList<>();

        Iterator<T> iterator = list.iterator();

        for (int i = 0; i < num; i++) {
            if (iterator.hasNext()) {
                T examplar = iterator.next();
                exemplars.add(examplar);
            } else {
                break;
            }
        }

        return exemplars;
    }
}

Related Tutorials