canonical example by Tabnine
private Double calculateAverageGrade(Map<String, List<Integer>> gradesList, String studentName) throws Exception { return Optional.ofNullable(gradesList.get(studentName)) .map(list -> list.stream().collect(Collectors.averagingDouble(x -> x))) .orElseThrow(() -> new Exception("Student not found - " + studentName)); }
@Override public OptionalDouble getValueFromAggregationQueryResult(Object value) { return Optional.ofNullable(value) .map(Number.class::cast) .map(Number::doubleValue) .map(OptionalDouble::of) .orElseGet(OptionalDouble::empty); }
/** * Determine a media type for the given resource, if possible. * @param resource the resource to introspect * @return the corresponding media type, or {@code null} if none found */ public static Optional<MediaType> getMediaType(@Nullable Resource resource) { return Optional.ofNullable(resource) .map(Resource::getFilename) .flatMap(MediaTypeFactory::getMediaType); }
@VisibleForTesting static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics) { return columnStatistics.stream() .map(MetastoreHiveStatisticsProvider::getDistinctValuesCount) .filter(OptionalLong::isPresent) .map(OptionalLong::getAsLong) .peek(distinctValuesCount -> verify(distinctValuesCount >= 0, "distinctValuesCount must be greater than or equal to zero")) .max(Long::compare) .map(Estimate::of) .orElse(Estimate.unknown()); }
private static <T, S extends Publisher<T>> S readWithMessageReaders( ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType, Function<HttpMessageReader<T>, S> readerFunction, Function<UnsupportedMediaTypeException, S> errorFunction, Supplier<S> emptySupplier) { if (VOID_TYPE.equals(elementType)) { return emptySupplier.get(); } MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType()) .orElse(MediaType.APPLICATION_OCTET_STREAM); return context.messageReaders().stream() .filter(reader -> reader.canRead(elementType, contentType)) .findFirst() .map(BodyExtractors::<T>cast) .map(readerFunction) .orElseGet(() -> { List<MediaType> mediaTypes = context.messageReaders().stream() .flatMap(reader -> reader.getReadableMediaTypes().stream()) .collect(Collectors.toList()); return errorFunction.apply( new UnsupportedMediaTypeException(contentType, mediaTypes, elementType)); }); }
public Node<E> findLeaf() { int leftDecendants = left.map(node -> node.descendants).orElse(0); int rightDecendants = right.map(node -> node.descendants).orElse(0); if (leftDecendants == 0 && rightDecendants == 0) { return left.orElse(right.orElse(this)); } if (leftDecendants > rightDecendants) { return left.get().findLeaf(); } if (rightDecendants > leftDecendants) { return right.get().findLeaf(); } // For ties just go left checkState(left.isPresent(), "Left child missing"); return left.get().findLeaf(); }
/** * Determine the media types for the given file name, if possible. * @param filename the file name plus extension * @return the corresponding media types, or an empty list if none found */ public static List<MediaType> getMediaTypes(@Nullable String filename) { return Optional.ofNullable(StringUtils.getFilenameExtension(filename)) .map(s -> s.toLowerCase(Locale.ENGLISH)) .map(fileExtensionToMediaTypes::get) .orElse(Collections.emptyList()); }
private static TypeSignature makeSignature(List<Field> fields) { int size = fields.size(); if (size == 0) { throw new IllegalArgumentException("Row type must have at least 1 field"); } List<TypeSignatureParameter> parameters = fields.stream() .map(field -> TypeSignatureParameter.of(new NamedTypeSignature(field.getName().map(name -> new RowFieldName(name, false)), field.getType().getTypeSignature()))) .collect(Collectors.toList()); return new TypeSignature(ROW, parameters); }
private ConnectorBucketNodeMap(int bucketCount, Optional<List<Node>> bucketToNode) { if (bucketCount <= 0) { throw new IllegalArgumentException("bucketCount must be positive"); } if (bucketToNode.isPresent() && bucketToNode.get().size() != bucketCount) { throw new IllegalArgumentException(format("Mismatched bucket count in bucketToNode (%s) and bucketCount (%s)", bucketToNode.get().size(), bucketCount)); } this.bucketCount = bucketCount; this.bucketToNode = bucketToNode.map(ArrayList::new).map(Collections::unmodifiableList); }
/** * Return method model for the given method on consumer side * * @param method method object * @return method model */ public ConsumerMethodModel getMethodModel(String method) { Optional<Map.Entry<Method, ConsumerMethodModel>> consumerMethodModelEntry = methodModels.entrySet().stream().filter(entry -> entry.getKey().getName().equals(method)).findFirst(); return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null); }
private static <T> HttpMessageWriter<T> findWriter( BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) { return context.messageWriters().stream() .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType)) .findFirst() .map(BodyInserters::<T>cast) .orElseThrow(() -> new IllegalStateException( "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\"")); }
public Type[] getRelationCoercion(Relation relation) { return Optional.ofNullable(relationCoercions.get(NodeRef.of(relation))) .map(types -> types.stream().toArray(Type[]::new)) .orElse(null); }
private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getDomains().get().entrySet().stream() .filter(entry -> isPathColumnHandle(entry.getKey())) .findFirst() .map(Map.Entry::getValue); }
private static <P extends Publisher<?>, M extends ReactiveHttpOutputMessage> Mono<Void> writeWithMessageWriters( M outputMessage, BodyInserter.Context context, P body, ResolvableType bodyType) { MediaType mediaType = outputMessage.getHeaders().getContentType(); return context.messageWriters().stream() .filter(messageWriter -> messageWriter.canWrite(bodyType, mediaType)) .findFirst() .map(BodyInserters::cast) .map(writer -> write(body, bodyType, mediaType, outputMessage, context, writer)) .orElseGet(() -> Mono.error(unsupportedError(bodyType, context, mediaType))); }
private static boolean isQGStatusUnchanged(QGChangeEvent qualityGateEvent, Optional<EvaluatedQualityGate> evaluatedQualityGate) { Optional<Metric.Level> previousStatus = qualityGateEvent.getPreviousStatus(); if (!previousStatus.isPresent() && !evaluatedQualityGate.isPresent()) { return true; } return previousStatus .map(previousQGStatus -> evaluatedQualityGate .filter(newQualityGate -> newQualityGate.getStatus() == previousQGStatus) .isPresent()) .orElse(false); }
private <T> List<T> parseMatchers( String configName, Config config, String delimiter, Function<String,T> matchFunc ) { String fullAccessProcedures = config.getValue( configName ).map( Object::toString ).orElse( "" ); if ( fullAccessProcedures.isEmpty() ) { return Collections.emptyList(); } else { return Stream.of( fullAccessProcedures.split( delimiter ) ).map( matchFunc ) .collect( Collectors.toList() ); } }
private static OptionalLong getTableParameterValue(QueryResult describeResult, String key) { verify(describeResult.getColumnsCount() == 3, "describe result is expected to have 3 columns"); for (List<Object> row : describeResult.rows()) { Optional<String> parameterKey = Optional.ofNullable(row.get(1)) .map(Object::toString) .map(String::trim); if (parameterKey.isPresent() && key.equals(parameterKey.get())) { return Optional.ofNullable(row.get(2)) .map(Object::toString) .map(String::trim) .map(TestHiveBasicTableStatistics::tryParse) .get(); } } return OptionalLong.empty(); }
/** * Checks whether all of the data buffers allocated by this factory have also been released. * If not, then an {@link AssertionError} is thrown. Typically used from a JUnit {@link After} * method. */ public void checkForLeaks() { this.created.stream() .filter(LeakAwareDataBuffer::isAllocated) .findFirst() .map(LeakAwareDataBuffer::leakError) .ifPresent(leakError -> { throw leakError; }); }
/** * Return the first {@link Locale} of the content languages, * as specified by the {@literal Content-Language} header. * <p>Returns {@code null} when the content language is unknown. * <p>Use {@code getValuesAsList(CONTENT_LANGUAGE)} if you need * to get multiple content languages.</p> * @since 5.0 */ @Nullable public Locale getContentLanguage() { return getValuesAsList(CONTENT_LANGUAGE) .stream() .findFirst() .map(Locale::forLanguageTag) .orElse(null); }