Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Collection;

import java.util.Iterator;

import java.util.function.Predicate;

public class Main {
    /**
     * Filter only items with a toString() value starting with prefix.
     * @param input
     * @param prefix
     * @param <V>
     */
    public static <V> void startsWith(Collection<V> input, final String prefix) {

        filter(input, (v) -> v.toString().startsWith(prefix));

    }

    /**
     * Filter the collection by applying a Predicate to each element. If the
     * predicate returns false, remove the element. If the input collection or
     * predicate is null, there is no change made.
     *
     * @param input
     * @param predicate
     * @param <V>
     * @return
     */
    public static <V> void filter(Collection<V> input, Predicate<V> predicate) {

        Iterator<V> iterator = input.iterator();

        while (iterator.hasNext()) {

            V value = iterator.next();

            if (!predicate.test(value)) {
                iterator.remove();
            }

        }

    }
}