All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.microsphere.lang.function.Streams Maven / Gradle / Ivy

The newest version!
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.microsphere.lang.function;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static io.microsphere.lang.function.Predicates.and;
import static io.microsphere.lang.function.Predicates.or;
import static java.util.stream.Collectors.toList;

/**
 * The utilities class for {@link Stream}
 *
 * @since 1.0.0
 */
public interface Streams {

    static  Stream stream(Iterable iterable) {
        return StreamSupport.stream(iterable.spliterator(), false);
    }

    static > Stream filterStream(S values, Predicate predicate) {
        return StreamSupport.stream(values.spliterator(), false).filter(predicate);
    }

    static > List filterList(S values, Predicate predicate) {
        return filterStream(values, predicate).collect(toList());
    }

    static > Set filterSet(S values, Predicate predicate) {
        // new Set with insertion order
        return filterStream(values, predicate).collect(LinkedHashSet::new, Set::add, Set::addAll);
    }

    static > S filter(S values, Predicate predicate) {
        final boolean isSet = Set.class.isAssignableFrom(values.getClass());
        return (S) (isSet ? filterSet(values, predicate) : filterList(values, predicate));
    }

    static > S filterAll(S values, Predicate... predicates) {
        return filter(values, and(predicates));
    }

    static > S filterAny(S values, Predicate... predicates) {
        return filter(values, or(predicates));
    }

    static  T filterFirst(Iterable values, Predicate... predicates) {
        return StreamSupport.stream(values.spliterator(), false)
                .filter(and(predicates))
                .findFirst()
                .orElse(null);
    }
}






© 2015 - 2024 Weber Informatics LLC | Privacy Policy