Issue with Java 8 Lambda for effective final while incrementing counts

后端 未结 3 1278
走了就别回头了
走了就别回头了 2021-01-26 17:04

I want to use Java 8 Lambda expression in following scenario but I am getting Local variable fooCount defined in an enclosing scope must be final or effectively final.

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 17:57

    There is a count method in stream to do counts for you.

    long fooCount = map.keySet().stream().filter(k -> k.contains("FOO")).count();
    long barCount = map.size() - fooCount;
    

    If you want parallelisation, change .stream() to .parallelStream().

    Alternatively, if you were trying to increment a variable manually, and use stream parallelisation, then you would want to use something like AtomicLong for thread safety. A simple variable, even if the compiler allowed it, would not be thread-safe.

提交回复
热议问题