当前位置: 首页>>代码示例>>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;未经允许,请勿转载。