gpt4 book ai didi

java - 比较两个列表 - 寻找更快、更有效的方法

转载 作者:行者123 更新时间:2023-12-01 13:52:43 24 4
gpt4 key购买 nike

我正在寻找一种更好的方法来比较两个“列表”。我的想法是:我有 2 个由字符串组成的列表。如果两个列表中的所有字符串都匹配,我的方法将返回 true。即

List(1) = "foo, foo1, foo2, foo3"

List(2) = "foo, foo1, foo2, foo3"

比较这两个列表时,如果所有字符串都匹配,则该方法返回 true。如果任何元素不匹配则返回 false。

我拥有(并且有效)的代码是这样的:但是我只是想知道是否有人能想到更好的解决方案来解决这个问题?

private boolean match(Context messageContext, ContextRule contextRule) {
if(contextRule.getMessageContext().getUser().equals(ContextRuleEvaluator.WILDCARD)
|| (contextRule.getMessageContext().getUser().equals(messageContext.getUser()))) {
if(contextRule.getMessageContext().getApplication().equals(ContextRuleEvaluator.WILDCARD)
|| (contextRule.getMessageContext().getApplication().equals(messageContext.getApplication()))) {
if(contextRule.getMessageContext().getService().equals(ContextRuleEvaluator.WILDCARD)
|| (contextRule.getMessageContext().getService().equals(messageContext.getService()))) {
if(contextRule.getMessageContext().getOperation().equals(ContextRuleEvaluator.WILDCARD)
|| (contextRule.getMessageContext().getOperation().equals(messageContext.getOperation()))) {
return true;
}
}
}
}

return false;

}

上下文

public interface Context {    
public String getUser();
public void setUser(String user);
public String getApplication();
public void setApplication(String application);
public String getService();
public void setService(String service);
public String getOperation();
public void setOperation(String operation);
}

上下文规则

public interface ContextRule {
public Context getMessageContext();
public int getAllowedConcurrentRequests();
}

最佳答案

我认为通过一些重构和应用 DRY,您的方法将和其他方法一样有效:

将匹配逻辑移至 Context 类中:

@Override
public boolean match(Context anotherContext) {
return match(this.getUser(), anotherContext.getUser()) &&
match(this.getApplication(), anotherContext.getApplication()) &&
match(this.getService(), anotherContext.getService()) &&
match(this.getOperation(), anotherContext.getOperation());
}

private boolean match(String thisString, String thatString) {
return thisString.equals(WILDCARD) || thisString.equals(thatString);
}

然后使用它:

private boolean match(Context messageContext, ContextRule contextRule) {
Context ruleContext = contextRule.getContext();
return ruleContext.match(messageContext);
}

关于java - 比较两个列表 - 寻找更快、更有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com