blob: b9ee683df737be6fc46af5dfa4e1e70b8b8e2128 [file] [log] [blame]
Aharoni, Pavel (pa0916)ca3cb012018-10-22 15:29:57 +03001/*-
2 * ============LICENSE_START=======================================================
3 * OSAM
4 * ================================================================================
5 * Copyright (C) 2018 AT&T
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
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
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=========================================================
19 */
20
21
22
23package org.onap.osam.utils;
24
25import java.util.Iterator;
26import java.util.Spliterator;
27import java.util.Spliterators;
28import java.util.function.Consumer;
29import java.util.function.Predicate;
30import java.util.stream.Stream;
31import java.util.stream.StreamSupport;
32
33public class Streams {
34 public static <R> Predicate<R> not(Predicate<R> predicate) {
35 return predicate.negate();
36 }
37
38 public static <T> Stream<T> fromIterator(final Iterator<T> iterator) {
39 Iterable<T> iterable = () -> iterator;
40 return StreamSupport.<T>stream(iterable.spliterator(), false);
41 }
42
43
44 // https://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate
45 private static <T> Spliterator<T> takeWhile(
46 Spliterator<T> splitr, Predicate<? super T> predicate) {
47 return new Spliterators.AbstractSpliterator<T>(splitr.estimateSize(), 0) {
48 boolean stillGoing = true;
49 @Override public boolean tryAdvance(Consumer<? super T> consumer) {
50 if (stillGoing) {
51 boolean hadNext = splitr.tryAdvance(elem -> {
52 if (predicate.test(elem)) {
53 consumer.accept(elem);
54 } else {
55 stillGoing = false;
56 }
57 });
58 return hadNext && stillGoing;
59 }
60 return false;
61 }
62 };
63 }
64
65 public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<? super T> predicate) {
66 return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false);
67 }
68
69}