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

The following examples show how to use java8.util.Optional#empty() . 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: FieldConverter.java    From ground-android with Apache License 2.0 6 votes vote down vote up
static Optional<Field> toField(ElementNestedObject em) {
  Field.Builder field = Field.newBuilder();
  switch (toEnum(Field.Type.class, em.getType())) {
    case TEXT:
      field.setType(Type.TEXT);
      break;
    case MULTIPLE_CHOICE:
      field.setType(Type.MULTIPLE_CHOICE);
      field.setMultipleChoice(MultipleChoiceConverter.toMultipleChoice(em));
      break;
    case PHOTO:
      field.setType(Type.PHOTO);
      break;
    default:
      return Optional.empty();
  }
  field.setRequired(em.getRequired() != null && em.getRequired());
  field.setId(em.getId());
  field.setLabel(getLocalizedMessage(em.getLabels()));
  return Optional.of(field.build());
}
 
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: ResponseJsonConverter.java    From ground-android with Apache License 2.0 5 votes vote down vote up
static Optional<Response> toResponse(Object obj) {
  if (obj instanceof String) {
    return TextResponse.fromString((String) obj);
  } else if (obj instanceof JSONArray) {
    return MultipleChoiceResponse.fromList(toList((JSONArray) obj));
  } else {
    Timber.e("Error parsing JSON in db of " + obj.getClass() + ": " + obj);
    return Optional.empty();
  }
}
 
Example 4
Source File: MultipleChoice.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public Optional<Integer> getIndex(String code) {
  for (int i = 0; i < getOptions().size(); i++) {
    if (getOptions().get(i).getCode().equals(code)) {
      return Optional.of(i);
    }
  }
  return Optional.empty();
}
 
Example 5
Source File: GuiTaskExecutor.java    From settlers-remake with MIT License 5 votes vote down vote up
private Optional<ILogicMovable> removeMovableThatCanMoveTo(List<ILogicMovable> movables, int x, int y) {
	for (Iterator<ILogicMovable> iterator = movables.iterator(); iterator.hasNext(); ) {
		ILogicMovable movable = iterator.next();
		if (canMoveTo(movable, x, y)) {
			iterator.remove();
			return Optional.of(movable);
		}
	}
	return Optional.empty();
}
 
Example 6
Source File: MultipleChoiceResponse.java    From ground-android with Apache License 2.0 5 votes vote down vote up
public static Optional<Response> fromList(List<String> codes) {
  if (codes.isEmpty()) {
    return Optional.empty();
  } else {
    return Optional.of(new MultipleChoiceResponse(codes));
  }
}
 
Example 7
Source File: MatrixHttpUser.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<_Presence> getPresence() {
    URL path = getClientPath("presence", mxId.getId(), "status");

    MatrixHttpRequest request = new MatrixHttpRequest(new Request.Builder().get().url(path));
    request.addIgnoredErrorCode(404);
    String body = execute(request);
    if (StringUtils.isBlank(body)) {
        return Optional.empty();
    }

    return Optional.of(new Presence(GsonUtil.parseObj(body)));
}
 
Example 8
Source File: SingleSelectDialogFactory.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private Optional<Response> getSelectedValue(Field field, List<Option> options) {
  if (checkedItem >= 0) {
    return Optional.of(
        new MultipleChoiceResponse(ImmutableList.of(options.get(checkedItem).getCode())));
  } else {
    return Optional.empty();
  }
}
 
Example 9
Source File: Basic.java    From streamsupport with GNU General Public License v2.0 5 votes vote down vote up
@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();
        }
    });
}
 
Example 10
Source File: GsonUtil.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Optional<JsonObject> findObj(JsonObject o, String key) {
    if (!o.has(key)) {
        return Optional.empty();
    }

    return Optional.ofNullable(o.getAsJsonObject(key));
}
 
Example 11
Source File: MatrixHttpRoom.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<JsonObject> getState(String type) {
    URL path = getClientPath("rooms", getAddress(), "state", type);

    MatrixHttpRequest request = new MatrixHttpRequest(new Request.Builder().get().url(path));
    request.addIgnoredErrorCode(404);
    String body = executeAuthenticated(request);
    if (StringUtils.isBlank(body)) {
        return Optional.empty();
    }

    return Optional.of(GsonUtil.parseObj(body));
}
 
Example 12
Source File: MatrixHttpRoom.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<JsonObject> getState(String type, String key) {
    URL path = getClientPath("rooms", roomId, "state", type, key);

    MatrixHttpRequest request = new MatrixHttpRequest(new Request.Builder().get().url(path));
    request.addIgnoredErrorCode(404);
    String body = executeAuthenticated(request);
    if (StringUtils.isBlank(body)) {
        return Optional.empty();
    }

    return Optional.of(GsonUtil.parseObj(body));
}
 
Example 13
Source File: TradingBuilding.java    From settlers-remake with MIT License 5 votes vote down vote up
@Override
public Optional<MaterialTypeWithCount> tryToTakeMaterial(int maxAmount) {
	if (!isTargetSet() || getPriority() == EPriority.STOPPED) { // if no target is set, or work is stopped don't give materials
		return Optional.empty();
	}

	List<? extends IRequestStack> potentialStacks = stream(getStacks()).filter(IRequestStack::hasMaterial).collect(Collectors.toList());

	if (potentialStacks.isEmpty()) {
		return Optional.empty();
	}

	EMaterialType resultMaterialType = potentialStacks.get(0).getMaterialType();
	int resultCount = 0;

	for (IRequestStack stack : potentialStacks) {
		if (stack.getMaterialType() != resultMaterialType) {
			continue;
		}

		while (resultCount < maxAmount && stack.pop()) {
			resultCount++;
		}

		if (resultCount >= maxAmount) {
			break;
		}
	}

	return Optional.of(new MaterialTypeWithCount(resultMaterialType, resultCount));
}
 
Example 14
Source File: MatrixHttpRoom.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<MatrixErrorInfo> tryLeave() {
    try {
        leave();
        return Optional.empty();
    } catch (MatrixClientRequestException e) {
        return e.getError();
    }
}
 
Example 15
Source File: Basic.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseThrowNull() throws Throwable {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(null);
}
 
Example 16
Source File: Loadable.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@NonNull
public static <T> Optional<T> getValue(LiveData<Loadable<T>> liveData) {
  return liveData.getValue() == null ? Optional.empty() : liveData.getValue().value();
}
 
Example 17
Source File: AbstractFieldViewModel.java    From ground-android with Apache License 2.0 4 votes vote down vote up
private Optional<String> validate(Field field, Optional<Response> response) {
  if (field.isRequired() && (response == null || response.isEmpty())) {
    return Optional.of(resources.getString(R.string.required_field));
  }
  return Optional.empty();
}
 
Example 18
Source File: Basic.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NoSuchElementException.class)
public void testEmptyGet() {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.get();
}
 
Example 19
Source File: TextResponse.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public static Optional<Response> fromString(String text) {
  return text.isEmpty() ? Optional.empty() : Optional.of(new TextResponse(text));
}
 
Example 20
Source File: GeoJsonTile.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public Optional<String> getId() {
  String s = json.optString(ID_KEY);
  return s.isEmpty() ? Optional.empty() : Optional.of(s);
}