[英]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. 我有一些使用Java 8功能编写的代码,这意味着流和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? 现在,我必须在使用Java 7的项目中重用这些代码。是否有可能使用IntelliJ自动重构代码?
For example, I have to refactor some code that looks like the following, into a simple for
/ while
loop. 例如,我必须将一些看起来如下的代码重构为一个简单的for
/ while
循环。
Arrays.stream(values)
.distinct()
.limit(2)
.count();
Yes, IntelliJ has "Replace Stream API chain with loop" refactor option. 是的,IntelliJ具有“使用循环替换流API链”重构选项。 It pops up after pressing Alt+Enter
after placing cursor on the Arrays.stream()
method: 将光标放在Arrays.stream()
方法后按Alt+Enter
后弹出:
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. 对于工作选项,项目语言级别必须为8或更高。
You really don't need that much of code for the current logic though(refactoring here seems not optimal and less readable to me atleast.) 你真的不需要那么多当前逻辑的代码(这里的重构似乎不是最优的,至少对我来说不太可读。)
What also works is simply using a Set
and working around its size: 什么也有效只是使用一个Set
并解决它的大小:
Set<String> set = new HashSet<>(values);
System.out.println(set.size() > 2 ? 2 : set.size());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.