Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.*;

import java.util.stream.Stream;

public class Main {
    /**
     * Shortcut for {@code filter($(c),clazz)}
     *
     * @param c     collection to be filtered. Must not be {@code null}.
     * @param clazz filter type of elements that will remain in the returned Stream.
     *              Must not be {@code null}.
     * @param <I>   type of input elements
     * @param <O>   type of output elements
     * @return Stream of elements in collection {@code c} that are of type O
     */
    public static <I, O> Stream<O> filter(Collection<I> c, Class<O> clazz) {
        return filter($(c), clazz);
    }

    /**
     * This is a shortcut for {@code (Stream<O>) s.filter(o -> clazz.isInstance(o))}.
     *
     * @param s     stream that's elements are filtered by type {@code clazz}. Must not be {@code null}.
     * @param clazz Type the elements of the input stream should be of to be part of the returned result stream.
     *              Must not be {@code null}.
     * @param <I>   Type of elements in input stream
     * @param <O>   Type of element remaining in the output stream
     * @return input stream filtered by type {@code O}
     * @throws NullPointerException when {@code clazz} or {@code s} is {@code null}.
     */
    @SuppressWarnings("unchecked") // we know the cast is safe, since all elements are of type O
    public static <I, O> Stream<O> filter(Stream<I> s, Class<O> clazz) throws NullPointerException {
        Objects.requireNonNull(clazz);
        Objects.requireNonNull(s);
        return (Stream<O>) s.filter(clazz::isInstance);
    }

    /**
     * This method is a shortcut for {@code c.stream()} if c is not {@code null}. If c is {@code null},
     * this method will return an empty stream.
     *
     * @param c   Collection to create a Stream from. If {@code null}, an empty stream will be returned.
     * @param <T> Type of elements in collection.
     * @return Stream created from collection {@code c}.
     */
    public static <T> Stream<T> $(Collection<T> c) {
        if (c == null) {
            return Stream.empty();
        }
        // else
        return c.stream();
    }
}