Java Code Examples for java8.util.Optional#isPresent()

The following examples show how to use java8.util.Optional#isPresent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AddFeatureDialogFragment.java    From ground-android with Apache License 2.0 6 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
  super.onCreateDialog(savedInstanceState);
  // TODO: Inject and use custom factory.
  Optional<Project> activeProject = Loadable.getValue(homeScreenViewModel.getActiveProject());
  if (!activeProject.isPresent()) {
    addFeatureRequestSubject.onError(new IllegalStateException("No active project"));
    return fail("Could not get active project");
  }
  Optional<Point> cameraPosition =
      Optional.ofNullable(mapContainerViewModel.getCameraPosition().getValue());
  if (!cameraPosition.isPresent()) {
    addFeatureRequestSubject.onError(new IllegalStateException("No camera position"));
    return fail("Could not get camera position");
  }
  return createDialog(activeProject.get(), cameraPosition.get());
}
 
Example 2
Source File: OptionalActivity.java    From AndroidAnimationExercise with Apache License 2.0 6 votes vote down vote up
private void elseUse() {
    Student student = new Student("lucy", 18);

    // 创建一个 为 Null 的 Optional
    Optional optional = Optional.empty();

    if (optional.isEmpty()) {
        System.out.println("optional is empty");
    }


    Optional<Student> studentOptional = Optional.ofNullable(student);
    // isPresent() 可以判断当前 Optional 是否为 Null
    if (studentOptional.isPresent()) {
        System.out.println("student is present");
    }
}
 
Example 3
Source File: DonkeyStrategy.java    From settlers-remake with MIT License 6 votes vote down vote up
protected boolean loadUp(ITradeBuilding tradeBuilding) {
	Optional<EMaterialType> materialType1 = tradeBuilding.tryToTakeMaterial(1).map(MaterialTypeWithCount::getMaterialType);
	Optional<EMaterialType> materialType2 = tradeBuilding.tryToTakeMaterial(1).map(MaterialTypeWithCount::getMaterialType);

	if (!materialType1.isPresent() && !materialType2.isPresent()) {
		reset();
		return false;

	} else {
		super.setMaterial(EMaterialType.BASKET);

		this.materialType1 = materialType1.orElse(null);
		this.materialType2 = materialType2.orElse(null);

		return true;
	}
}
 
Example 4
Source File: CollectorsTest.java    From streamsupport with GNU General Public License v2.0 5 votes vote down vote up
@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());
    }
}
 
Example 5
Source File: NewSinglePlayerSetupViewModel.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
public void startGame() {
	int maxPlayers = mapLoader.getMaxPlayers();

	List<PlayerSlotPresenter> playerSlotPresenters = Arrays.asList(getPlayerSlots().getValue());
	PlayerSetting[] playerSettings = new PlayerSetting[maxPlayers];
	byte humanPlayerId = playerSlotPresenters.get(0).getPlayerId();

	for (int i = 0; i < maxPlayers; i++) {
		final int position = i;

		Optional<PlayerSlotPresenter> player = stream(playerSlotPresenters)
				.filter(playerSlotPresenter -> playerSlotPresenter.getStartPosition().asByte() == position)
				.findFirst();

		if (player.isPresent()) {
			playerSettings[position] = player.get().getPlayerSettings();
		} else {
			playerSettings[position] = new PlayerSetting();
		}
	}

	JSettlersGame game = new JSettlersGame(mapLoader, 4711L, humanPlayerId, playerSettings);

	gameStarter.setStartingGame(game.start());
	showMapEvent.call();
}
 
Example 6
Source File: MainGrid.java    From settlers-remake with MIT License 5 votes vote down vote up
final boolean isNavigable(int x, int y) {
	Optional<ShortPoint2D> blockingOptional = HexGridArea.stream(x, y, 0, 2)
														 .filterBounds(width, height)
														 .filter((x1, y1) -> !landscapeGrid.getLandscapeTypeAt(x1, y1).isWater || objectsGrid.getMapObjectAt(x1, y1, EMapObjectType.DOCK) != null)
														 .getFirst();
	return !blockingOptional.isPresent();
}
 
Example 7
Source File: MainGrid.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
public FerryEntrance ferryAtPosition(ShortPoint2D position, byte playerId) {
	Optional<ILogicMovable> ferryOptional = HexGridArea.stream(position.x, position.y, 0, Constants.MAX_FERRY_ENTRANCE_SEARCH_DISTANCE)
													   .filterBounds(width, height)
													   .filter((x, y) -> landscapeGrid.getLandscapeTypeAt(x, y).isWater())
													   .iterateForResult((x, y) -> {
														   ILogicMovable movable = movableGrid.getMovableAt(x, y);
														   return Optional.ofNullable(movable).filter(m -> m.getMovableType() == EMovableType.FERRY);
													   });

	if (!ferryOptional.isPresent()) {
		return null;
	}

	ILogicMovable ferry = ferryOptional.get();
	ShortPoint2D ferryPosition = ferry.getPosition();
	Optional<ShortPoint2D> entranceOptional = HexGridArea.stream(ferryPosition.x, ferryPosition.y, 0, Constants.MAX_FERRY_ENTRANCE_SEARCH_DISTANCE)
														 .filterBounds(width, height)
														 .filter((x, y) -> !isBlocked(x, y))
														 .getFirst();

	if (!entranceOptional.isPresent()) {
		return null;
	}

	return new FerryEntrance(ferry, entranceOptional.get());
}
 
Example 8
Source File: OriginalMapFileContentReader.java    From settlers-remake with MIT License 5 votes vote down vote up
private MapResourceInfo findAndDecryptFilePartSafe(EOriginalMapFilePartType partType) throws MapLoadException {
	Optional<MapResourceInfo> filePart = findAndDecryptFilePart(partType);
	if (filePart.isPresent()) {
		return filePart.get();
	} else {
		throw new MapLoadException("No " + partType + " information available in mapfile!");
	}
}
 
Example 9
Source File: OriginalMapFileContentReader.java    From settlers-remake with MIT License 5 votes vote down vote up
void readStacks() throws MapLoadException {
	Optional<MapResourceInfo> filePartOptional = findAndDecryptFilePart(EOriginalMapFilePartType.STACKS);

	if (filePartOptional.isPresent()) {
		MapResourceInfo filePart = filePartOptional.get();
		// - file position
		int pos = filePart.offset;

		// - Number of buildings
		int stackCount = readBEIntFrom(pos);
		pos += 4;

		// - safety check
		if ((stackCount * 8 > filePart.size) || (stackCount < 0)) {
			throw new MapLoadException("wrong number of stacks in map File: " + stackCount);
		}

		// - read all Stacks
		for (int i = 0; i < stackCount; i++) {

			int posX = readBEWordFrom(pos);
			pos += 2;
			int posY = readBEWordFrom(pos);
			pos += 2;

			int stackType = readByteFrom(pos++);
			int count = readByteFrom(pos++);

			pos += 2; // not used - maybe: padding to size of 8 (2 INTs)

			// -------------
			// - update data
			mapData.setStack(posX, posY, stackType, count);
		}
	}
}
 
Example 10
Source File: OriginalMapFileContentReader.java    From settlers-remake with MIT License 5 votes vote down vote up
void readSettlers() throws MapLoadException {
	Optional<MapResourceInfo> filePartOptional = findAndDecryptFilePart(EOriginalMapFilePartType.SETTLERS);

	if (filePartOptional.isPresent()) {
		MapResourceInfo filePart = filePartOptional.get();
		// - file position
		int pos = filePart.offset;

		// - Number of buildings
		int settlerCount = readBEIntFrom(pos);
		pos += 4;

		// - safety check
		if ((settlerCount * 6 > filePart.size) || (settlerCount < 0)) {
			throw new MapLoadException("wrong number of settlers in map File: " + settlerCount);
		}

		// - read all Stacks
		for (int i = 0; i < settlerCount; i++) {

			int party = readByteFrom(pos++);
			int settlerType = readByteFrom(pos++);

			int posX = readBEWordFrom(pos);
			pos += 2;
			int posY = readBEWordFrom(pos);
			pos += 2;

			// -------------
			// - update data
			mapData.setSettler(posX, posY, settlerType, party);
		}
	}
}
 
Example 11
Source File: MatrixJsonEventFactory.java    From matrix-java-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
public static _MatrixEvent get(JsonObject obj) {
    String type = obj.get("type").getAsString();

    if ("m.room.member".contentEquals(type)) {
        return new MatrixJsonRoomMembershipEvent(obj);
    } else if ("m.room.power_levels".contentEquals(type)) {
        return new MatrixJsonRoomPowerLevelsEvent(obj);
    } else if ("m.room.avatar".contentEquals(type)) {
        return new MatrixJsonRoomAvatarEvent(obj);
    } else if ("m.room.name".contentEquals(type)) {
        return new MatrixJsonRoomNameEvent(obj);
    } else if ("m.room.topic".contentEquals(type)) {
        return new MatrixJsonRoomTopicEvent(obj);
    } else if ("m.room.aliases".contentEquals(type)) {
        return new MatrixJsonRoomAliasesEvent(obj);
    } else if (_RoomCanonicalAliasEvent.Type.contentEquals(type)) {
        return new MatrixJsonRoomCanonicalAliasEvent(obj);
    } else if ("m.room.message".contentEquals(type)) {
        return new MatrixJsonRoomMessageEvent(obj);
    } else if ("m.receipt".contentEquals(type)) {
        return new MatrixJsonReadReceiptEvent(obj);
    } else if ("m.room.history_visibility".contentEquals(type)) {
        return new MatrixJsonRoomHistoryVisibilityEvent(obj);
    } else if (_TagsEvent.Type.contentEquals(type)) {
        return new MatrixJsonRoomTagsEvent(obj);
    } else if (_DirectEvent.Type.contentEquals(type)) {
        return new MatrixJsonDirectEvent(obj);
    } else {
        Optional<String> timestamp = EventKey.Timestamp.findString(obj);
        Optional<String> sender = EventKey.Sender.findString(obj);

        if (!timestamp.isPresent() || !sender.isPresent()) {
            return new MatrixJsonEphemeralEvent(obj);
        } else {
            Optional<String> rId = EventKey.RoomId.findString(obj);
            if (rId.isPresent()) {
                return new MatrixJsonRoomEvent(obj);
            }

            return new MatrixJsonPersistentEvent(obj);
        }
    }
}
 
Example 12
Source File: OriginalMapFileContentReader.java    From settlers-remake with MIT License 4 votes vote down vote up
void readBuildings() throws MapLoadException {
	hasBuildings = false;

	Optional<MapResourceInfo> filePartOptional = findAndDecryptFilePart(EOriginalMapFilePartType.BUILDINGS);

	if (filePartOptional.isPresent()) {
		MapResourceInfo filePart = filePartOptional.get();
		// - file position
		int pos = filePart.offset;

		// - Number of buildings
		int buildingsCount = readBEIntFrom(pos);
		pos += 4;

		// - safety check
		if ((buildingsCount * 12 > filePart.size) || (buildingsCount < 0)) {
			throw new MapLoadException("wrong number of buildings in map File: " + buildingsCount);
		}

		hasBuildings = true;

		// - read all Buildings
		for (int i = 0; i < buildingsCount; i++) {

			int party = readByteFrom(pos++); // - Party starts with 0
			int buildingType = readByteFrom(pos++);
			int posX = readBEWordFrom(pos);
			pos += 2;
			int posY = readBEWordFrom(pos);
			pos += 2;

			pos++; // not used - maybe a filling byte to make the record 12 Byte (= 3 INTs) long or unknown?!

			// -----------
			// - number of soldier in building is saved as 4-Bit (=Nibble):
			int countSword1 = readHighNibbleFrom(pos);
			int countSword2 = readLowNibbleFrom(pos);
			pos++;

			int countArcher2 = readHighNibbleFrom(pos);
			int countArcher3 = readLowNibbleFrom(pos);
			pos++;

			int countSword3 = readHighNibbleFrom(pos);
			int countArcher1 = readLowNibbleFrom(pos);
			pos++;

			int countSpear3 = readHighNibbleFrom(pos);
			// low nibble is a not used count
			pos++;

			int countSpear1 = readHighNibbleFrom(pos);
			int countSpear2 = readLowNibbleFrom(pos);
			pos++;

			// -------------
			// - update data
			mapData.setBuilding(posX, posY, buildingType, party, countSword1, countSword2, countSword3, countArcher1, countArcher2, countArcher3, countSpear1, countSpear2, countSpear3);
		}
	}
}