當前位置: 首頁>>代碼示例>>Java>>正文


Java Optional.orElse方法代碼示例

本文整理匯總了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;
    }
 
開發者ID:mbari-media-management,項目名稱:vars-annotation,代碼行數:25,代碼來源:ImageArchiveServiceDecorator.java

示例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);
}
 
開發者ID:staylward,項目名稱:streams-dojo,代碼行數:27,代碼來源:ExampleFindFirstTest.java

示例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);
}
 
開發者ID:NymphWeb,項目名稱:nymph,代碼行數:17,代碼來源:WebXmlStarter.java

示例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("");
}
 
開發者ID:ehabqadah,項目名稱:in-situ-processing-datAcron,代碼行數:17,代碼來源:AbstractStatisticsWrapper.java

示例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);
		}
	}
 
開發者ID:PacktPublishing,項目名稱:Java-Data-Science-Made-Easy,代碼行數:22,代碼來源:DataImputation.java

示例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);
}
 
開發者ID:3wks,項目名稱:generator-thundr-gae-react,代碼行數:11,代碼來源:ReferenceDataService.java

示例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;
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:11,代碼來源:GroupModBuilder.java

示例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());
	}
}
 
開發者ID:NymphWeb,項目名稱:nymph,代碼行數:13,代碼來源:DefaultWebApplicationBeansFactory.java

示例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");
}
 
開發者ID:commercetools,項目名稱:commercetools-sync-java,代碼行數:15,代碼來源:CommonTypeUpdateActionUtilsTest.java

示例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;
	
}
 
開發者ID:michaelcgood,項目名稱:PagingAndSortingRepository-Example,代碼行數:36,代碼來源:ClientController.java

示例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();
}
 
開發者ID:NymphWeb,項目名稱:nymph,代碼行數:14,代碼來源:MainStarter.java

示例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
}
 
開發者ID:tomwhite,項目名稱:set-game,代碼行數:33,代碼來源:FindCardShapeFeatures.java

示例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));
}
 
開發者ID:alphagov,項目名稱:verify-service-provider,代碼行數:13,代碼來源:AttributeTranslationService.java

示例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);
}
 
開發者ID:Shynixn,項目名稱:PetBlocks,代碼行數:13,代碼來源:DataBaseRepository.java

示例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));
}
 
開發者ID:JeffreyFalgout,項目名稱:junit5-extensions,代碼行數:11,代碼來源:GuiceExtension.java


注:本文中的java.util.Optional.orElse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。