本文整理汇总了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);
}
}
});
}
}
});
}
示例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);
}
});
}
示例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);
}
}
示例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;
}
示例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();
}
示例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();
}
示例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();
}
示例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"));
});
}
示例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();
}
}
示例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);
});
}
示例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);
}
}
示例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);
}
示例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));
}
示例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)));
});
}
示例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;
}