1 /* 2 * Copyright 2023 Code Intelligence GmbH 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.code_intelligence.jazzer.mutation.support; 18 19 import static java.util.stream.Collectors.toList; 20 21 import java.util.AbstractMap.SimpleEntry; 22 import java.util.List; 23 import java.util.NoSuchElementException; 24 import java.util.Optional; 25 import java.util.function.IntFunction; 26 import java.util.stream.Stream; 27 28 public final class StreamSupport { StreamSupport()29 private StreamSupport() {} 30 toBooleanArray(Stream<Boolean> stream)31 public static boolean[] toBooleanArray(Stream<Boolean> stream) { 32 List<Boolean> list = stream.collect(toList()); 33 boolean[] array = new boolean[list.size()]; 34 for (int i = 0; i < list.size(); i++) { 35 array[i] = list.get(i); 36 } 37 return array; 38 } 39 40 /** 41 * @return the first present value, otherwise {@link Optional#empty()} 42 */ findFirstPresent(Stream<Optional<T>> stream)43 public static <T> Optional<T> findFirstPresent(Stream<Optional<T>> stream) { 44 return stream.filter(Optional::isPresent).map(Optional::get).findFirst(); 45 } 46 47 /** 48 * @return an array with the values if all {@link Optional}s are present, otherwise 49 * {@link Optional#empty()} 50 */ toArrayOrEmpty( Stream<Optional<T>> stream, IntFunction<T[]> newArray)51 public static <T> Optional<T[]> toArrayOrEmpty( 52 Stream<Optional<T>> stream, IntFunction<T[]> newArray) { 53 try { 54 return Optional.of(stream.map(Optional::get).toArray(newArray)); 55 } catch (NoSuchElementException e) { 56 return Optional.empty(); 57 } 58 } 59 60 /** 61 * Return a stream containing the optional value if present, otherwise an empty stream. 62 * 63 * @return stream containing the optional value 64 */ getOrEmpty(Optional<T> optional)65 public static <T> Stream<T> getOrEmpty(Optional<T> optional) { 66 return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); 67 } 68 entry(K key, V value)69 public static <K, V> SimpleEntry<K, V> entry(K key, V value) { 70 return new SimpleEntry<>(key, value); 71 } 72 } 73