Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downgrade Java 8 streams to Java 7 loops in Intellij IDEA

I have some code written using Java 8 features, which means streams and lambdas. Now, I have to reuse such code in a project that uses Java 7. Is there the possibility to automatically refactor the code using IntelliJ?

For example, I have to refactor some code that looks like the following, into a simple for / while loop.

Arrays.stream(values)
      .distinct()
      .limit(2)
      .count();
like image 687
riccardo.cardin Avatar asked Feb 07 '19 13:02

riccardo.cardin


1 Answers

Yes, IntelliJ has "Replace Stream API chain with loop" refactor option. It pops up after pressing Alt+Enter after placing cursor on the Arrays.stream() method:

enter image description here

It will produce code like:

long count = 0L;
long limit = 2;
Set<Integer> uniqueValues = new HashSet<>();
for (int i : new int[]{1, 2, 3}) {
    if (uniqueValues.add(i)) {
        if (limit-- == 0) break;
        count++;
    }
}
System.out.println(count);

For the option to work the project language level has to be 8 or higher.

like image 100
Karol Dowbecki Avatar answered Nov 01 '22 20:11

Karol Dowbecki