背景
  • IDEA 又搞黄色了!
    IDEA告警:Can be replaced with ‘.values().stream()‘_其它
详解

可替换为.values().stream()
检查信息:通知可以简化的流API调用链。它可以避免遍历集合时创建多余的临时对象。
此检查替换了以下调用链:

collection.stream().forEach() → collection.forEach()
collection.stream().collect(toList/toSet/toCollection())new CollectionType<>(collection)
collection.stream().toArray() → collection.toArray()
Arrays.asList().stream() → Arrays.stream() or Stream.of()
IntStream.range(0, array.length).mapToObj(idx -> array[idx]) → Arrays.stream(array)
IntStream.range(0, list.size()).mapToObj(idx -> list.get(idx)) → list.stream()
Collections.singleton().stream() → Stream.of()
Collections.emptyList().stream() → Stream.empty()
stream.filter().findFirst().isPresent() → stream.anyMatch()
stream.collect(counting()) → stream.count()
stream.collect(maxBy()) → stream.max()
stream.collect(mapping()) → stream.map().collect()
stream.collect(reducing()) → stream.reduce()
stream.collect(summingInt()) → stream.mapToInt().sum()
stream.mapToObj(x -> x) → stream.boxed()
stream.map(x -> {...; return x;}) → stream.peek(x -> ...)
!stream.anyMatch() → stream.noneMatch()
!stream.anyMatch(x -> !(...)) → stream.allMatch()
stream.map().anyMatch(Boolean::booleanValue) -> stream.anyMatch()
IntStream.range(expr1, expr2).mapToObj(x -> array[x]) -> Arrays.stream(array, expr1, expr2)
Collection.nCopies(count, ...) -> Stream.generate().limit(count)
stream.sorted(comparator).findFirst() -> Stream.min(comparator)

替换语义在某些情况下可能会有细微的差别。例如

  • Collections.synchronizedList(...).forEach() 同步时,Collections.synchronizedList(...).stream().forEach()不同步
  • collect(Collectors.maxBy())将返回空的Optional,如果结果元素为null,而 Stream.max()在这种情况下将抛NullPointerException