java8 Stream 流對象返回單一值案例

通過返回第一個
// org.springframework.boot.logging.LoggingSystem
/**
 * Detect and return the logging system in use. Supports Logback and Java Logging.
 * @param classLoader the classloader
 * @return the logging system
 */
public static LoggingSystem get(ClassLoader classLoader) {
	String loggingSystem = System.getProperty(SYSTEM_PROPERTY);
	if (StringUtils.hasLength(loggingSystem)) {
		if (NONE.equals(loggingSystem)) {
			return new NoOpLoggingSystem();
		}
		return get(classLoader, loggingSystem);
	}
	return SYSTEMS.entrySet()
				   // 獲取流對象
				  .stream()
				  // 過濾
				  .filter((entry) -> ClassUtils.isPresent(entry.getKey(), classLoader))
				  // 映射
			      .map((entry) -> get(classLoader, entry.getValue()))
			      // 返回第一個值
			      .findFirst()
			      // 不存在則拋出異常
				  .orElseThrow(() -> new IllegalStateException("No suitable logging system located"));
}
// org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
	MutablePropertySources propertySources = environment.getPropertySources();
	propertySources.stream()
				   .map(JsonPropertyValue::get)
				   .filter(Objects::nonNull)
				   .findFirst()
			       .ifPresent((v) -> processJson(environment, v));
}
通過拼接
// org.springframework.boot.convert.CollectionToDelimitedStringConverter
private Object convert(Collection<?> source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source.isEmpty()) {
		return "";
	}
	return source.stream()
				  // 進行映射
				 .map((element) -> convertElement(element, sourceType, targetType))
			      // 結果收集 
			     .collect(Collectors.joining(getDelimiter(sourceType)));
}
判斷布爾值
private boolean consumesRequestBody(Method method) {
	return Stream.of(method.getParameters())
			.anyMatch((parameter) -> parameter.getAnnotation(Selector.class) == null);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章