How to use the non-permanent variable in Java8 filters / filters?

advertisements

In my use case I would like to update the value of a variable and reference the same in next iteration in streams.

But the java compiler is giving me error. Here is my code

static String convertList(
  List<Map.Entry<String, String>> map,
  String delimiter,
  long maxLength
) {
    long currentLength = 0L;
    return map.stream()
    .map(e->e.getKey() + "=" + e.getValue())
    .filter(p->{
      long pLength = p.getBytes(StandardCharsets.UTF_8).length;
      currentLength = currentLength + pLength;
      if (currentLength <= maxLength) {
        return true;
      } else {
        return false;
      }
    })
  .collect(Collectors.joining(delimiter));
}

I am trying to get the values from the list to a string until the length [till this iteration] <= maxlength

could someone help me fix this? I am getting Local variables referenced from a lambda expression must be final or effectively final error.


You should use a loop and break; once your condition is fulfilled. It is faster because it can bail out early (the stream would traverse the whole list) and does not violate the specification of Stream.filter which requires that the passed predicate must be stateless.

Stream<T> filter(Predicate<? super T> predicate)

predicate - a non-interfering, stateless predicate to apply to each element to determine if it should be included