Creates new collection that contains only element whose string representation starts with prefix It uses raw collection - not parameterized. - Java java.util

Java examples for java.util:Collection Creation

Description

Creates new collection that contains only element whose string representation starts with prefix It uses raw collection - not parameterized.

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "book2s.com");
        String prefix = "book2s.com";
        System.out.println(withPrefixRaw(c, prefix));
    }/*  ww w  .  java 2  s  . c  om*/

    /**
     * Creates new collection that contains only element whose string
     * representation starts with prefix It uses raw collection - not
     * parameterized. There is no {@link SuppressWarnings} annotation so IDE
     * will probably report rawtype and/or unchecked warnings.
     * 
     * @param c
     *            raw collection to create prefixed collection from
     * @param prefix
     *            to use as filter
     * @return collection without nulls
     */
    public static Collection withPrefixRaw(Collection c, String prefix) {
        Collection prefixed = new ArrayList();
        Iterator iterator = c.iterator();
        while (iterator.hasNext()) {
            Object o = iterator.next();
            if (o != null && o.toString().startsWith(prefix)) {
                prefixed.add(o);
            }
        }
        return prefixed;
    }
}

Related Tutorials