Issue with Java 8 Lambda for effective final while incrementing counts

后端 未结 3 1277
走了就别回头了
走了就别回头了 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:56

    To get both numbers, matching and non-matching elements, you can use

    Map result = map.keySet().stream()
        .collect(Collectors.partitioningBy(k -> k.contains("FOO"), Collectors.counting()));
    long fooCount = result.get(true);
    long barCount = result.get(false);
    

    But since your source is a Map, which knows its total size, and want to calculate a percentage, for which barCount is not needed, this specific task can be solved as

    private int calculateFooPercentage() {
        return (int)(map.keySet().stream().filter(k -> k.contains("FOO")).count()
                     *100/map.size());
    }
    

    Both variants are thread safe, i.e. changing stream() to parallelStream() will perform the operation in parallel, however, it’s unlikely that this operation will benefit from parallel processing. You would need humongous key strings or maps to get a benefit…

提交回复
热议问题