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

标签 java performance list

我正在寻找一种更好的方法来比较两个“列表”。我的想法是:我有 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/

相关文章:

mysql - SQL语句运行缓慢

c# - "% Time in GC"性能计数器是什么意思

python - 用同一个键合并两个字典

python - 计算两个列表中的频率,Python

java - Java 8 中的编译器是否将有效的最终变量解释为最终变量?

java - 我和大O搞混了

java - 扩展 JFrame 创建新的 JFrame 对象

java - 我已经编写了一个线程,但如何将其添加到我的 main 方法中?

java - 增强的 for 循环与手动处理对象

c# - 仅查找列表中的相等单词存在于字符串中