Inspectopedia Help

Stream API call chain can be simplified

Reports stream API call chains that can be simplified. Simplification will often avoid some temporary object creation during collection traversal.

The inspection replaces the following call chains:

  • 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)

  • optional.orElseGet(() -> { throw new ...; })optional.orElseThrow()

Note that the replacement semantics may have minor differences in some cases. For example, Collections.synchronizedList(...).stream().forEach() is not synchronized while Collections.synchronizedList(...).forEach() is synchronized. Also, collect(Collectors.maxBy()) returns an empty Optional if the resulting element is null while Stream.max() throws NullPointerException in this case.

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

SimplifyStreamApiCallChains
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Verbose or redundant code constructs

This inspection depends on the Java feature 'Stream and Optional API' which is available since Java 8.

Availability

By default bundled with

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin

Java, 241.18072

Last modified: 18 June 2024