Skip to content
Advertisement

Java 8 edit stream elements

I need to filter and modify the values of the filtered object. The logic that must be filtered is given below.

    boolean isUpdated = false;
    for (final Identifier identifier : identifiers)
    {
      if (identifier.type == type)
      {
        identifier.identifier = identifierValue;
        identifier.label = label;
        identifier.comment = comment;
        isUpdated = true;
        break;
      }

I have tried it like this. But how can we set the value of isUpdated = true using java 8?

    Arrays.stream(identifiers).filter(a -> a.type == type).forEach(i -> {
      i.identifier = identifierValue;
      i.label = label;
      i.comment = comment;
    });

Answer

Base on the logic given, findFirst should be used as you stop after the first instance is found.

    boolean isUpdated = false;
    Optional<Identifier> result = Arrays.stream(identifiers).filter(i -> i.type==type).findFirst();
    result.ifPresent(i -> {
        i.identifier = identifierValue;
        i.label = lebel;
        i.comment = comment;
    });
    isUpdated = result.isPresent();
Advertisement