本文整理汇总了Java中java8.util.Optional类的典型用法代码示例。如果您正苦于以下问题:Java Optional类的具体用法?Java Optional怎么用?Java Optional使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Optional类属于java8.util包,在下文中一共展示了Optional类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: onCreate
import java8.util.Optional; //导入依赖的package包/类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solicitados);
context=this;
//Cargo el menú lateral y pongo el nombre del proyecto a el Toolbar
SliderMenu sliderMenu = new SliderMenu(context, this);
sliderMenu.inicializateToolbar("Solicitudes");
usuarioSesion = Sesion.getUsuario(context);
RecyclerView recyclerViewSolicitudes = (RecyclerView) findViewById(R.id.recyclerSolicitudes);
Optional<ArrayList<SolicitudUnion>> listOptional = StreamSupport.stream(Almacen.getProyectos()).filter(proyecto -> proyecto.getIdPropietario() == usuarioSesion.getId()).map(proyecto -> proyecto.getSolicitudes()).findAny();
if(listOptional.isPresent())
adapterSolicitudes = new AdapterSolicitudes(context, listOptional.get());
else
adapterSolicitudes = new AdapterSolicitudes(context, new ArrayList<>());
//Establezco el recyclerview con las redes sociales
LinearLayoutManager llm = new LinearLayoutManager(context);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerViewSolicitudes.setLayoutManager(llm);
recyclerViewSolicitudes.setAdapter(adapterSolicitudes);
recyclerViewSolicitudes.addItemDecoration(new DividerItemDecoration(recyclerViewSolicitudes.getContext(),
llm.getOrientation()));
}
示例2: testSequentialShortCircuitTerminal
import java8.util.Optional; //导入依赖的package包/类
@Test(groups = { "serialization-hostile" })
public void testSequentialShortCircuitTerminal() {
// The sorted op for sequential evaluation will buffer all elements when accepting
// then at the end sort those elements and push those elements downstream
List<Integer> l = Arrays.asList(5, 4, 3, 2, 1);
// Find
assertEquals(StreamSupport.stream(l).sorted().findFirst(), Optional.of(1));
assertEquals(StreamSupport.stream(l).sorted().findAny(), Optional.of(1));
assertEquals(unknownSizeStream(l).sorted().findFirst(), Optional.of(1));
assertEquals(unknownSizeStream(l).sorted().findAny(), Optional.of(1));
// Match
assertEquals(StreamSupport.stream(l).sorted().anyMatch(i -> i == 2), true);
assertEquals(StreamSupport.stream(l).sorted().noneMatch(i -> i == 2), false);
assertEquals(StreamSupport.stream(l).sorted().allMatch(i -> i == 2), false);
assertEquals(unknownSizeStream(l).sorted().anyMatch(i -> i == 2), true);
assertEquals(unknownSizeStream(l).sorted().noneMatch(i -> i == 2), false);
assertEquals(unknownSizeStream(l).sorted().allMatch(i -> i == 2), false);
}
示例3: getIntersection
import java8.util.Optional; //导入依赖的package包/类
/**
* Returns the intersection point between this edge and the specified edge.
*
* <b>NOTE:</b> returns an empty optional if the edges are parallel or if
* the intersection point is not inside the specified edge segment
*
* @param e edge to intersect
* @return the intersection point between this edge and the specified edge
*/
public Optional<Vector3d> getIntersection(Edge e) {
Optional<Vector3d> closestPOpt = getClosestPoint(e);
if (!closestPOpt.isPresent()) {
// edges are parallel
return Optional.empty();
}
Vector3d closestP = closestPOpt.get();
if (e.contains(closestP)) {
return closestPOpt;
} else {
// intersection point outside of segment
return Optional.empty();
}
}
示例4: boundaryPolygonsOfPlaneGroup
import java8.util.Optional; //导入依赖的package包/类
private static List<Polygon> boundaryPolygonsOfPlaneGroup(
List<Polygon> planeGroup) {
List<Polygon> polygons = boundaryPathsWithHoles(
boundaryPaths(boundaryEdgesOfPlaneGroup(planeGroup)));
System.out.println("polygons: " + polygons.size());
List<Polygon> result = new ArrayList<>(polygons.size());
for (Polygon p : polygons) {
Optional<List<Polygon>> holesOfPresult
= p.
getStorage().getValue(Edge.KEY_POLYGON_HOLES);
if (!holesOfPresult.isPresent()) {
result.add(p);
} else {
result.addAll(PolygonUtil.concaveToConvex(p));
}
}
return result;
}
示例5: min
import java8.util.Optional; //导入依赖的package包/类
public Optional<ShortPoint2D> min(IIntCoordinateFunction function) {
MutableInt bestX = new MutableInt(Integer.MIN_VALUE);
MutableInt bestY = new MutableInt();
MutableInt bestValue = new MutableInt(Integer.MAX_VALUE);
iterate((x, y) -> {
int currValue = function.apply(x, y);
if (currValue < bestValue.value) {
bestValue.value = currValue;
bestX.value = x;
bestY.value = y;
}
return true;
});
if (bestX.value != Integer.MIN_VALUE) {
return Optional.of(new ShortPoint2D(bestX.value, bestY.value));
} else {
return Optional.empty();
}
}
示例6: testIterateForResultStopsAfterResult
import java8.util.Optional; //导入依赖的package包/类
@Test
public void testIterateForResultStopsAfterResult() {
int expectedVisits = 5;
Object expectedResultObject = new Object();
MutableInt counter = new MutableInt(0);
Optional<Object> actualResultObject = HexGridArea.stream(10, 10, 3, 10).iterateForResult((x, y) -> {
counter.value++;
if (counter.value == expectedVisits) {
return Optional.of(expectedResultObject);
} else {
return Optional.empty();
}
});
assertEquals(expectedVisits, counter.value);
assertTrue(actualResultObject.isPresent());
assertSame(expectedResultObject, actualResultObject.get());
}
示例7: unCheckElement
import java8.util.Optional; //导入依赖的package包/类
private void unCheckElement(int position){
View view =gridView.getChildAt(position);
ImageView seleccionado = (ImageView) view.findViewById(R.id.elemento_area);
seleccionado.setVisibility(View.GONE);
Optional<Area> areaOptional = StreamSupport.stream(areasBack).filter(area1 -> area1.getId() == ((Area) getItem(position)).getId()).findAny();
if(areaOptional.isPresent())
areasBack.remove(areaOptional.get());
}
示例8: resetFields
import java8.util.Optional; //导入依赖的package包/类
private void resetFields() {
scrollView.removeView(scoreView);
scrollView = null;
scoreView = null;
midiToXMLRenderer = null;
closeMidiReceiver();
longTapAction = Optional.empty();
}
示例9: testEmptyOrElseThrow
import java8.util.Optional; //导入依赖的package包/类
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseThrow(new Supplier<ObscureException>() {
@Override
public ObscureException get() {
return new ObscureException();
}
});
}
示例10: testOfNullable
import java8.util.Optional; //导入依赖的package包/类
@Test(groups = "unit")
public void testOfNullable() {
Optional<String> instance = Optional.ofNullable(null);
assertFalse(instance.isPresent());
instance = Optional.ofNullable("Duke");
assertTrue(instance.isPresent());
assertEquals(instance.get(), "Duke");
}
示例11: testWithUnorderedInfiniteStream
import java8.util.Optional; //导入依赖的package包/类
public void testWithUnorderedInfiniteStream() {
// These tests should short-circuit, otherwise will fail with a time-out
// or an OOME
// Note that since the streams are unordered and any element is requested
// (a non-deterministic process) the only assertion that can be made is
// that an element should be found
Optional<Integer> oi = RefStreams.iterate(1, i -> i + 1).unordered().parallel().distinct().findAny();
assertTrue(oi.isPresent());
oi = ThreadLocalRandom.current().ints().boxed().parallel().distinct().findAny();
assertTrue(oi.isPresent());
}
示例12: assertValue
import java8.util.Optional; //导入依赖的package包/类
@Override
void assertValue(U value, Supplier<Stream<T>> source, boolean ordered)
throws Exception {
Optional<U> reduced = source.get().map(mapper).reduce(reducer);
if (value == null)
assertTrue(!reduced.isPresent());
else if (!reduced.isPresent()) {
assertEquals(value, identity);
}
else {
assertEquals(value, reduced.get());
}
}
示例13: testInfiniteRangeFindFirst
import java8.util.Optional; //导入依赖的package包/类
public void testInfiniteRangeFindFirst() {
Integer first = RefStreams.iterate(0, i -> i + 1).filter(i -> i > 10000).findFirst().get();
assertEquals(first, RefStreams.iterate(0, i -> i + 1).parallel().filter(i -> i > 10000).findFirst().get());
// Limit is required to transform the infinite stream to a finite stream
// since the exercising requires a finite stream
withData(TestData.Factory.ofSupplier(
"", () -> RefStreams.iterate(0, i -> i + 1).filter(i -> i > 10000).limit(20000))).
terminal(s->s.findFirst()).expectedResult(Optional.of(10001)).exercise();
}
示例14: getValue
import java8.util.Optional; //导入依赖的package包/类
/**
* Returns a property.
*
* @param <T> property type
* @param key key
* @return the property; an empty {@link java.util.Optional} will be
* returned if the property does not exist or the type does not match
*/
public <T> Optional<T> getValue(String key) {
Object value = map.get(key);
try {
return Optional.ofNullable((T) value);
} catch (ClassCastException ex) {
return Optional.empty();
}
}
示例15: iterateForResult
import java8.util.Optional; //导入依赖的package包/类
public <T> Optional<T> iterateForResult(ICoordinateFunction<Optional<T>> function) {
Mutable<Optional<T>> result = new Mutable<>(Optional.empty());
iterate((x, y) -> {
Optional<T> currResult = function.apply(x, y);
if (currResult.isPresent()) {
result.object = currResult;
return false;
} else {
return true;
}
});
return result.object;
}