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


Java Optional.ifPresent方法代碼示例

本文整理匯總了Java中java.util.Optional.ifPresent方法的典型用法代碼示例。如果您正苦於以下問題:Java Optional.ifPresent方法的具體用法?Java Optional.ifPresent怎麽用?Java Optional.ifPresent使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.Optional的用法示例。


在下文中一共展示了Optional.ifPresent方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: remap

import java.util.Optional; //導入方法依賴的package包/類
@Override
protected void remap() {
    Optional<ClassNode> classNode = findNode(TestMappings.class.getName());
    classNode.ifPresent((cn) -> {
        for (MethodNode method : cn.methods) {
            TypeNameEnforcer returnType = TypeNameEnforcer.getReturnType(method);
            if (returnType.getJvmStandard().equals("java/lang/String")) {
                method.instructions.iterator().forEachRemaining((insnNode) -> {
                    if (insnNode instanceof LdcInsnNode) {
                        LdcInsnNode ldcInsnNode = (LdcInsnNode) insnNode;
                        String payload = (String) ldcInsnNode.cst;
                        if (!payload.equals("oops")) {
                            MethodRef methodRef = createObfMd(method);
                            MethodRef methodRef1 = createRemappedMd("correct", method);
                            getMappings().putMethod(methodRef, methodRef1);
                        }
                    }
                });
            }
        }
    });
}
 
開發者ID:PizzaCrust,項目名稱:GraphiteMappings,代碼行數:23,代碼來源:TestMappings.java

示例2: onClickRestore

import java.util.Optional; //導入方法依賴的package包/類
/**
 * Restores all settings to default. Some settings like {@link Property#DEVELOPMENT} and
 * {@link Property#SHOW_CHANGELOG} won't be reset, since the user can't change those anyways.
 */
@SuppressWarnings("static-method") // Can't be static because of FXML injection
@FXML
private void onClickRestore() {
	final Alert alert = new Alert(AlertType.CONFIRMATION, Client.lang.getString("sureYouWantToRestoreSettings"), ButtonType.YES, ButtonType.NO);
	alert.setTitle(Client.lang.getString("restoreSettingsToDefault"));
	Client.insertAlertOwner(alert);

	final Optional<ButtonType> result = alert.showAndWait();

	result.ifPresent(button -> {
		if (button == ButtonType.YES) {
			restoreApplicationSettings();
			LegacySettingsController.restoreLegacySettings();

			// Reapply theme, since it might have been changed
			Client.getInstance().applyTheme();
			// Assure the view that the displays the correct data.
			Client.getInstance().reloadViewIfLoaded(View.SETTINGS);
		}
	});
}
 
開發者ID:Bios-Marcel,項目名稱:ServerBrowser,代碼行數:26,代碼來源:SettingsController.java

示例3: switchTab

import java.util.Optional; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
public static <T extends AbstractTabController> void switchTab(Class<T> type, Consumer<T> afterSwitch) {

    Optional<AbstractTabController> tabController = tabControllerMap.values().stream()
            .filter(controller -> controller.getClass().equals(type))
            .findFirst();


    tabController.ifPresent(c -> {
        tabs.getSelectionModel().select(c.getTab());
        if (afterSwitch != null) {
            afterSwitch.accept((T) c);
        }
    });

    if (!tabController.isPresent()) {
        LOG.error("Tab controller not found for type " + type);
    }
}
 
開發者ID:yiding-he,項目名稱:redisfx,代碼行數:20,代碼來源:Tabs.java

示例4: getOperations

import java.util.Optional; //導入方法依賴的package包/類
/**
 * Returns the list of operations for the single item resource.
 *
 * @return the list of operations for the single item resource
 * @review
 */
public List<Operation> getOperations() {
	List<Operation> operations = new ArrayList<>();

	Optional<DeleteItemConsumer> deleteConsumerOptional =
		getDeleteConsumerOptional();

	if (deleteConsumerOptional.isPresent()) {
		operations.add(new Operation(DELETE, _name + "/delete"));
	}

	Optional<Form> formOptional = getFormOptional();

	formOptional.ifPresent(
		form -> operations.add(
			new Operation(form, UPDATE, _name + "/update")));

	return operations;
}
 
開發者ID:liferay,項目名稱:com-liferay-apio-architect,代碼行數:25,代碼來源:ItemRoutes.java

示例5: process

import java.util.Optional; //導入方法依賴的package包/類
private PropertyTree process(PropertyTree meta, SiteConfig siteConfig, ImmutableList<Category> categories) {
	Builder builder = FixedPropertyTree.builder()
			.copyOf(meta);

	for (PostProcessing.Category cat : categories) {
		Optional<Tree> tree = siteConfig.tree(cat.tree());
		tree.ifPresent(t -> {
			ImmutableList<String> sourceVal = meta.findList(String.class, Splitter.on(".").split(cat.source()));
			ImmutableSet<String> allParents = t.allParentsOf(sourceVal);
			ImmutableSet<String> allCategories = Sets.union(allParents, Sets.newHashSet(sourceVal)).immutableCopy();
			allCategories.forEach(c -> {
				builder.put(cat.name(), c);
			});
		});
	}

	return builder.build();
}
 
開發者ID:flapdoodle-oss,項目名稱:de.flapdoodle.solid,代碼行數:19,代碼來源:SiteConfigPostProcessor.java

示例6: renameImage

import java.util.Optional; //導入方法依賴的package包/類
public void renameImage(String path,String file_to_rename) {
     TextInputDialog input = new TextInputDialog(file_to_rename.substring(0, file_to_rename.length()-4)+"1"+file_to_rename.substring(file_to_rename.length()-4));
        Optional<String> change = input.showAndWait();
        
        change.ifPresent((String change_event) -> {
            try {
                Files.move(new File(path).toPath(),new File(new File(path).getParent()+File.separator+change_event).toPath());
            } catch (IOException ex) {
               Alert a = new Alert(AlertType.ERROR);
               a.setTitle("Rename");
               a.setHeaderText("Error while renaming the file.");
               a.setContentText("Error code: "+e.getErrorInfo(ex)+"\n"+e.getErrorMessage(ex));
               a.showAndWait();
            }
     });
        System.gc();
}
 
開發者ID:Obsidiam,項目名稱:joanne,代碼行數:18,代碼來源:ImageManager.java

示例7: filter

import java.util.Optional; //導入方法依賴的package包/類
private static ImmutableList<Node> filter(ImmutableList<Node> nodeTree, ImmutableSet<String> knownNames, ImmutableSet<String> src, int level) {
	ImmutableList.Builder<Node> builder = ImmutableList.builder();

	for (String current : src) {
		if (!knownNames.contains(current)) {
			if (level==0) {
				builder.add(Node.builder().name(current).build());
			}
		} else {
			Optional<Node> matchingNode = nodeTree.stream()
				.filter(n -> n.name().equals(current))
				.findAny();
			matchingNode.ifPresent(node -> {
				builder.add(Node.builder()
						.name(current)
						.addAllChildren(filter(node.children(), knownNames, src, level+1))
						.build());
			});
		}
	}
	return builder.build();
}
 
開發者ID:flapdoodle-oss,項目名稱:de.flapdoodle.solid,代碼行數:23,代碼來源:Tree.java

示例8: testReadData

import java.util.Optional; //導入方法依賴的package包/類
@Test
public void testReadData() {
    final Optional<ResourceData> data = VersionedResource.read(directory, "trellis:repository/versioned", MAX);
    assertTrue(data.isPresent());
    data.ifPresent(d -> {
        assertEquals("trellis:repository/versioned", d.getId());
        assertEquals("http://www.w3.org/ns/ldp#BasicContainer", d.getLdpType());
        assertEquals("http://example.org/receiver/inbox", d.getInbox());
        assertTrue(d.getUserTypes().contains("http://example.org/types/Foo"));
        assertTrue(d.getUserTypes().contains("http://example.org/types/Bar"));
    });
}
 
開發者ID:trellis-ldp-archive,項目名稱:trellis-rosid-file,代碼行數:13,代碼來源:VersionedResourceTest.java

示例9: service

import java.util.Optional; //導入方法依賴的package包/類
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BeanContext beanContext = ContextListener.getBeanContext();
    // 開始
    try {
        LOGGER.debug("[Samurai] request [{}]", req.getRequestURI());
        BeanContextManager.set(beanContext);
        Optional<RequestHandler> handler = requestHandlers.parallelStream()
                .filter(requestHandler -> req.getRequestURI().matches(requestHandler.getPatternStr()))
                .findAny();
        if (!handler.isPresent()) {
            LOGGER.debug("[Samurai] can't find pattern matched to [{}]", req.getRequestURI());
        } else {
            LOGGER.debug("[Samurai] find controller [{}] match mapping [{}]", handler.get().getController().getClass().getName(), req.getRequestURI());
            addRequestAndResponseToBeanContext(beanContext, req, resp);
            handler.ifPresent(requestHandler -> requestHandler.handler(req, resp, new Object[]{}));
            LOGGER.debug("[Samurai] request complete [{}]", req.getRequestURI());
        }
    } catch (Exception e) {
        // TODO 異常
        e.printStackTrace();
    } finally {
        beanContext.removeRequestBeans();
        BeanContextManager.remove();
    }

}
 
開發者ID:omsfuk,項目名稱:Samurai,代碼行數:28,代碼來源:DispatcherServlet.java

示例10: testArgMaxForRow

import java.util.Optional; //導入方法依賴的package包/類
@Test(dataProvider = "parallel")
public void testArgMaxForRow(boolean parallel) {
    final DataFrame<String,String> frame = TestDataFrames.random(Double.class, 10, 100000).applyDoubles(v -> Math.random());
    final Optional<DataFrameValue<String,String>> match = parallel ? frame.rowAt(5).parallel().max(DataFrameValue.doubleComparator()) : frame.rowAt(5).max(DataFrameValue.doubleComparator());
    assertTrue(match.isPresent());
    match.ifPresent(v -> {
        final double minExpected = frame.rowAt(5).stats().max();
        final double minActual = frame.data().getDouble(5, v.colOrdinal());
        assertEquals(minActual, minExpected, 0.00001);
    });
}
 
開發者ID:zavtech,項目名稱:morpheus-core,代碼行數:12,代碼來源:MinMaxTests.java

示例11: startMinecraftClicked

import java.util.Optional; //導入方法依賴的package包/類
@FXML
private void startMinecraftClicked(ActionEvent event) {
	try {
		ServerInfo serverInfo = serverInfoService.getValue();
		Optional<String> ip = serverInfo.getIp();
		ip.ifPresent(ServerList::addOrReplace);

		startMinecraft();
	} catch (IOException e) {
		LOGGER.info("Error while starting minecraft: {}", e.getMessage());
		LogUtil.stacktrace(LOGGER, e);
	}
}
 
開發者ID:Azzurite,項目名稱:MinecraftServerSync,代碼行數:14,代碼來源:StartMinecraftButton.java

示例12: fun1

import java.util.Optional; //導入方法依賴的package包/類
private static void fun1() {
    GridInterface startGrid = GridUtils.getEmptyGrid(250, 250);
    PatternInterface pattern = PatternUtils.getClassicPattern();

    Solver solver = new Solver(startGrid, pattern);
    Optional<Solution> firstSolution = solver.findFirstSolution();

    firstSolution.ifPresent(System.out::println);
}
 
開發者ID:florian-mollin,項目名稱:lights-out-solver,代碼行數:10,代碼來源:Examples.java

示例13: LockFreePool

import java.util.Optional; //導入方法依賴的package包/類
private LockFreePool(final Supplier<Future<T>> supplier, final Optional<Integer> maxSize,
    final Optional<Integer> maxWaiters,
    final Optional<Duration> validationInterval, final ScheduledExecutorService scheduler) {
  this.supplier = supplier;
  this.sizeSemaphore = semaphore(maxSize);
  this.waitersSemaphore = semaphore(maxWaiters);
  // TODO is this the best data structure?
  this.items = new ConcurrentLinkedQueue<>();
  this.waiters = new ConcurrentLinkedQueue<>();
  validationInterval.ifPresent(i -> scheduleValidation(i, scheduler));
}
 
開發者ID:traneio,項目名稱:ndbc,代碼行數:12,代碼來源:LockFreePool.java

示例14: testMembershipTriples1

import java.util.Optional; //導入方法依賴的package包/類
@Test
public void testMembershipTriples1() {
    final Optional<ConstraintViolation> res = svc.constrainedBy(LDP.IndirectContainer,
            domain, asGraph("/invalidMembershipTriple.ttl", domain + "foo"))
        .filter(v -> v.getConstraint().equals(Trellis.InvalidRange)).findFirst();
    assertTrue(res.isPresent());
    res.ifPresent(violation -> {
        assertEquals(Trellis.InvalidRange, violation.getConstraint());
        assertTrue(violation.getTriples().contains(rdf.createTriple(rdf.createIRI(domain + "foo"),
                        LDP.hasMemberRelation, LDP.contains)));
    });
}
 
開發者ID:trellis-ldp-archive,項目名稱:trellis-constraint-rules,代碼行數:13,代碼來源:LdpConstraintsTest.java

示例15: getValue

import java.util.Optional; //導入方法依賴的package包/類
@Override
public double getValue(double rate) {
    Optional<KeyFrame> frameOpt = keyFrames.stream().filter(keyFrame -> keyFrame.inAnimation(rate)).findFirst();
    frameOpt.ifPresent(frame -> {
        Animation animation = frame.getAnimation();
        double r = frame.keyFrameRate(rate);
        value = animation.getValue(r);
    });
    return value;
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:11,代碼來源:KeyFrameAnimation.java


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