trim Collection - Android java.util

Android examples for java.util:Collection

Description

trim Collection

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "book2s.com");
        int numberOfElements = 42;
        trimCollection(collection, numberOfElements);
    }/*from   w ww .j a v  a  2 s. c om*/

    public static void trimCollection(Collection collection,
            int numberOfElements) {
        if (collection.size() < numberOfElements) {
            return;
        }

        numberOfElements = collection.size() - numberOfElements;
        Iterator it = collection.iterator();
        int counter = 0;

        while (it.hasNext()) {
            if (counter <= numberOfElements) {
                it.next();
                counter++;
            }
            it.remove();
        }
    }
}

Related Tutorials