2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.vid.utils;
23 import java.util.Iterator;
24 import java.util.Spliterator;
25 import java.util.Spliterators;
26 import java.util.function.Consumer;
27 import java.util.function.Predicate;
28 import java.util.stream.Stream;
29 import java.util.stream.StreamSupport;
31 public class Streams {
34 // hide the implicit public constructor
37 public static <R> Predicate<R> not(Predicate<R> predicate) {
38 return predicate.negate();
41 public static <T> Stream<T> fromIterator(final Iterator<T> iterator) {
42 Iterable<T> iterable = () -> iterator;
43 return StreamSupport.stream(iterable.spliterator(), false);
46 public static <T> Stream<T> fromIterable(final Iterable<T> iterable) {
47 return StreamSupport.stream(iterable.spliterator(), false);
51 // https://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate
52 private static <T> Spliterator<T> takeWhile(
53 Spliterator<T> splitr, Predicate<? super T> predicate) {
54 return new Spliterators.AbstractSpliterator<T>(splitr.estimateSize(), 0) {
55 boolean stillGoing = true;
56 @Override public boolean tryAdvance(Consumer<? super T> consumer) {
58 boolean hadNext = splitr.tryAdvance(elem -> {
59 if (predicate.test(elem)) {
60 consumer.accept(elem);
65 return hadNext && stillGoing;
72 public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<? super T> predicate) {
73 return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false);