我想把我的代码缩短一点。我有4个IFs,它们在做同样的事情,但是需要一个与对象不同的属性。一种不同的感觉。我用loopElement循环那些ifs。
if (!toCompareElement.getSomething().contains(loopElement.getSomething())) {
// Some code with loopElement.getSomething()
}
if (!toCompareElement.getSomethingElse().contains(loopElement.getSomethingElse())) {
// Some code with loopElement.getSomethingElse()
}
if (!toCompareElement.getSomethingDifferent().contains(loopElement.getSomethingDifferent())) {
// Some code with loopElement.getSomethingDifferent()
}
if (!toCompareElement.getDifferentSomething().contains(loopElement.getDifferentSomething())) {
// Some code with loopElement.getDifferentSomething()
}发布于 2022-08-03 11:04:42
您可以编写一个函数来概括您的if语句的逻辑(尽管我不清楚toCompareElement和loopElement是否具有相同的类型,或者后者是否是前者的集合:
import java.util.function.Consumer;
import java.util.function.Function;
interface Container {
boolean contains(Container e);
}
interface Element {
Container getSomething();
Container getSomethingElse();
}
public class Operation {
public static void elementOp(Function<Element,Container> extractor, Consumer<Element> operation, Element toCompare, Element loop) {
if (!extractor.apply(toCompare).contains(extractor.apply(loop))) {
operation.accept(loop);
}
}
public static void main(String[] args) {
Element toCompareElement = ...;
Element loopElement = ...;
elementOp(Element::getSomething, e -> {}, toCompareElement, loopElement);
elementOp(Element::getSomethingElse, e -> {}, toCompareElement, loopElement);
}
}这是在假设所有Element方法都返回Container实例并且一个Container可以包含另一个实例的情况下编写的。您可能需要将该类型更改为其他类型。你问题的这一部分还不清楚。
https://stackoverflow.com/questions/73219406
复制相似问题