本文整理汇总了Java中java.util.Optional.orElse方法的典型用法代码示例。如果您正苦于以下问题:Java Optional.orElse方法的具体用法?Java Optional.orElse怎么用?Java Optional.orElse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Optional
的用法示例。
在下文中一共展示了Optional.orElse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: buildName
import java.util.Optional; //导入方法依赖的package包/类
public static String buildName(UUID videoReferenceUuid, VideoIndex videoIndex, String ext) {
if (!ext.startsWith(".")) {
ext = "." + ext;
}
// index - uuid
Optional<Timecode> timecode = videoIndex.getTimecode();
Optional<Duration> elapsedTime = videoIndex.getElapsedTime();
Optional<Instant> timestamp = videoIndex.getTimestamp();
String idx;
if (timecode.isPresent()) {
idx = timecode.get().toString().replace(':', '_');
}
else if (elapsedTime.isPresent()) {
idx = elapsedTime.get().toMillis() + "";
}
else {
Instant t = timestamp.orElse(Instant.now());
idx = timeFormat.format(t);
}
return idx + "-" + videoReferenceUuid + ext;
}
示例2: shouldReturnBookThatContainsSpecialCharacters
import java.util.Optional; //导入方法依赖的package包/类
@Test
public void shouldReturnBookThatContainsSpecialCharacters() throws Exception {
// Given
List<Book> normalBooks = asList(
new Book("Test", 10),
new Book("Lord of the rings", 15),
new Book("Dune", 20)
);
List<Book> specialBooks = asList(
new Book("Tést", 25),
new Book("The hitchhiker's guide to the galaxy", 30),
new Book("\uD83D\uDC4C", 35)
);
List<Book> allBooks = new ArrayList<>();
allBooks.addAll(normalBooks);
allBooks.addAll(specialBooks);
// When
Optional<Book> result = ExampleFindFirst.findFirstSpecialBook(allBooks);
// Then
assertThat(result.isPresent()).isTrue();
Book value = result.orElse(null);
assertThat(specialBooks).contains(value);
}
示例3: contextInitialized
import java.util.Optional; //导入方法依赖的package包/类
@Override
public void contextInitialized(ServletContextEvent sce) {
// 加载配置文件
ServletContext context = sce.getServletContext();
loadConfig(context.getInitParameter(CONFIGURATIONS_PARAM_NAME));
// 实例化bean处理器
Optional<String> handler = getConfiguration().getBeansHandler();
String finalClass = handler.orElse(DEFAULT_BEANS_HANDLER);
BeansHandler beansHandler = BasicUtil.newInstance(finalClass);
getBeansFactory().setBeansHandler(beansHandler);
getBeansFactory().setConfiguration(getConfiguration());
// 将所有bean对象注册到bean容器
getBeansFactory().register();
loadServlets(context);
}
示例4: getDetectedAreasStr
import java.util.Optional; //导入方法依赖的package包/类
public static String getDetectedAreasStr(Set<Area> detectedAreas) {
if (detectedAreas == null) {
return "";
}
Optional<String> joinedString =
detectedAreas.stream().map(area -> area.getId()).reduce(new BinaryOperator<String>() {
@Override
public String apply(String t, String u) {
return t + AREAS_DELIMITER + u;
}
});
return joinedString.orElse("");
}
示例5: tempExample
import java.util.Optional; //导入方法依赖的package包/类
public static void tempExample(){
// double[] tempList = new double[365];
// for(int x = 0; x < tempList.length; x++){
// tempList[x] = Math.random()*100;
// }
// tempList[5] = 0;
// double sum = 0;
// for(double d : tempList){
// out.println(d);
// sum += d;
// }
// out.println(sum/365);
String useName = "";
String[] nameList = {"Amy","Bob","Sally","Sue","Don","Rick",null,"Betsy"};
Optional<String> tempName;
for(String name : nameList){
tempName = Optional.ofNullable(name);
useName = tempName.orElse("DEFAULT");
out.println("Name to use = " + useName);
}
}
示例6: getTransformer
import java.util.Optional; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private <T extends ReferenceData> Function<T, ReferenceDataDto> getTransformer(Class<T> referenceDataClass) {
Optional transformer = customTransformers
.entrySet()
.stream()
.filter(entry -> entry.getKey().isAssignableFrom(referenceDataClass))
.map(Map.Entry::getValue)
.findFirst();
return (Function<T, ReferenceDataDto>) transformer.orElse(ReferenceData.TO_DTO_TRANSFORMER);
}
示例7: GroupModBuilder
import java.util.Optional; //导入方法依赖的package包/类
private GroupModBuilder(GroupBuckets buckets, GroupId groupId,
GroupDescription.Type type, OFFactory factory,
Optional<Long> xid, Optional<DriverService> driverService) {
this.buckets = buckets;
this.groupId = groupId;
this.type = type;
this.factory = factory;
this.xid = xid.orElse((long) 0);
this.driverService = driverService;
}
示例8: initBeansExpandComponents
import java.util.Optional; //导入方法依赖的package包/类
private void initBeansExpandComponents() {
// bean的动态代理处理器
Optional<Object> proxy = beansComponent.getComponent(EnableBeanProxyHandler.class);
setBeansProxyHandler((BeansProxy) proxy.orElse(null));
autoInjectBeans.setBeansProxyHandler(proxyHandler);
Optional<Object> register = beansComponent.getComponent(EnableBeanRegister.class);
BeansRegister beansRegister = (BeansRegister) register.orElse(null);
if (beansRegister != null) {
container.putAll(beansRegister.registerBeans());
}
}
示例9: buildUpdateActionForLocalizedStrings_WithEmptyOldFields_ShouldBuildUpdateAction
import java.util.Optional; //导入方法依赖的package包/类
@Test
public void buildUpdateActionForLocalizedStrings_WithEmptyOldFields_ShouldBuildUpdateAction() {
final LocalizedString oldLocalisedString = LocalizedString.of(new HashMap<>());
final LocalizedString newLocalisedString = LocalizedString.of(LOCALE, "Milch");
final UpdateAction<Category> mockUpdateAction = ChangeName.of(
LocalizedString.of(LOCALE, MOCK_OLD_CATEGORY_NAME));
final Optional<UpdateAction<Category>> updateActionForLocalizedStrings =
buildUpdateAction(oldLocalisedString, newLocalisedString, () -> mockUpdateAction);
UpdateAction<Category> categoryUpdateAction = updateActionForLocalizedStrings.orElse(null);
assertThat(categoryUpdateAction).isNotNull();
assertThat(categoryUpdateAction.getAction()).isEqualTo("changeName");
}
示例10: homepage
import java.util.Optional; //导入方法依赖的package包/类
@GetMapping("/")
public ModelAndView homepage(@RequestParam("pageSize") Optional<Integer> pageSize,
@RequestParam("page") Optional<Integer> page){
if(clientrepository.count()!=0){
;//pass
}else{
addtorepository();
}
ModelAndView modelAndView = new ModelAndView("index");
//
// Evaluate page size. If requested parameter is null, return initial
// page size
int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
// Evaluate page. If requested parameter is null or less than 0 (to
// prevent exception), return initial size. Otherwise, return value of
// param. decreased by 1.
int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;
// print repo
System.out.println("here is client repo " + clientrepository.findAll());
Page<ClientModel> clientlist = clientrepository.findAll(new PageRequest(evalPage, evalPageSize));
System.out.println("client list get total pages" + clientlist.getTotalPages() + "client list get number " + clientlist.getNumber());
PagerModel pager = new PagerModel(clientlist.getTotalPages(),clientlist.getNumber(),BUTTONS_TO_SHOW);
// add clientmodel
modelAndView.addObject("clientlist",clientlist);
// evaluate page size
modelAndView.addObject("selectedPageSize", evalPageSize);
// add page sizes
modelAndView.addObject("pageSizes", PAGE_SIZES);
// add pager
modelAndView.addObject("pager", pager);
return modelAndView;
}
示例11: initBeansFactory
import java.util.Optional; //导入方法依赖的package包/类
/**
* 初始化beanFactory
*/
protected void initBeansFactory() {
// 实例化bean处理器
getBeansFactory().setConfiguration(getConfiguration());
Optional<String> handler = getConfiguration().getBeansHandler();
String handlerClass = handler.orElse(DEFAULT_BEANS_HANDLER);
BeansHandler beansHandler = BasicUtil.newInstance(handlerClass);
getBeansFactory().setBeansHandler(beansHandler);
// 将所有bean对象注册到bean工厂
getBeansFactory().register();
}
示例12: find
import java.util.Optional; //导入方法依赖的package包/类
@Override
public double[] find(BufferedImage image, boolean debug) throws IOException {
// Based on code from http://boofcv.org/index.php?title=Example_Binary_Image
ListDisplayPanel panel = debug ? new ListDisplayPanel() : null;
List<Shape> shapes = ImageProcessingPipeline.fromBufferedImage(image, panel)
.gray()
.medianBlur(3) // this is fairly critical
.edges()
.dilate()
.contours()
.polygons(0.05, 0.05)
.getExternalShapes();
int expectedWidth = 40 * 3; // 40mm
int expectedHeight = 20 * 3; // 20mm
int tolerancePct = 40;
List<Shape> filtered = GeometryUtils.filterByArea(shapes, expectedWidth, expectedHeight, tolerancePct);
List<Shape> nonOverlapping = GeometryUtils.filterNonOverlappingBoundingBoxes(filtered);
Optional<double[]> cardShapeFeatures = nonOverlapping.stream()
.map(Shape::getPolygon)
.map(p -> new double[] { p.size(), p.isConvex() ? 1 : 0 })
.findFirst();
if (debug) {
ShowImages.showWindow(panel, getClass().getSimpleName(), true);
}
return cardShapeFeatures.orElse(null); // improve
}
示例13: translateAttributes
import java.util.Optional; //导入方法依赖的package包/类
public static Attributes translateAttributes(AttributeStatement attributeStatement) {
List<Attribute> statementAttributes = attributeStatement.getAttributes();
VerifiableAttribute<String> verifiableFirstName = getVerifiableStringAttribute(statementAttributes, "firstname", "firstname_verified");
VerifiableAttribute<String> verifiableMiddleName = getVerifiableStringAttribute(statementAttributes, "middlename", "middlename_verified");
VerifiableAttribute<String> verifiableSurname = getVerifiableStringAttribute(statementAttributes, "surname", "surname_verified");
VerifiableAttribute<LocalDate> verifiableDob = getVerifiableDateAttribute(statementAttributes, "dateofbirth", "dateofbirth_verified");
VerifiableAttribute<Address> verifiableAddress = getVerifiableAddressAttribute(statementAttributes, "currentaddress", "currentaddress_verified");
Optional<List<VerifiableAttribute<Address>>> addressHistory = getVerifiableAddressListAttribute(statementAttributes, "addresshistory");
Optional<String> cycle3 = getStringAttributeValue(statementAttributes, "cycle_3");
return new Attributes(verifiableFirstName, verifiableMiddleName, verifiableSurname, verifiableDob, verifiableAddress, addressHistory.orElse(null), cycle3.orElse(null));
}
示例14: getById
import java.util.Optional; //导入方法依赖的package包/类
/**
* Returns the item of the given id
*
* @param id id
* @return item
*/
@Override
@Deprecated
public T getById(long id) {
final Optional<T> tmp = this.getFromId(id);
return tmp.orElse(null);
}
示例15: getKey
import java.util.Optional; //导入方法依赖的package包/类
private static Key<?> getKey(Optional<Class<?>> containingElement, Parameter parameter) {
Class<?> clazz =
containingElement.orElseGet(() -> parameter.getDeclaringExecutable().getDeclaringClass());
TypeToken<?> classType = TypeToken.of(clazz);
Type resolvedType = classType.resolveType(parameter.getParameterizedType()).getType();
Optional<Key<?>> key =
getOnlyBindingAnnotation(parameter).map(annotation -> Key.get(resolvedType, annotation));
return key.orElse(Key.get(resolvedType));
}