我可以将一堆 if 语句组合成一个对象吗?

Can I combine a bunch of if statements into an object?

我有一个包含数千个单行句子的 ArrayList,我想搜索大约 50 个关键词。如果它包含这些关键字之一,我希望它将与该关键字对应的双精度值添加到数组中。检查完所有数组的匹配项后,我想总结数组的总数。

目前我有类似的东西,除了数组列表和双变量列表要大得多:

import java.util.ArrayList;

public class searchArrayList {

public static void main(String[] args){


String subject2 = "The color of the ball is blue."; 
String subject3 = "The building is white.";
String subject4 = "Red is my favorite color.";  
String subject5 = "Black and blue are the team colors";



    ArrayList<Double> arrlist = new ArrayList<Double>();
    ArrayList<Double> difflist = new ArrayList<Double>();

    double Black = 10.1;
    double Blue = 1.6;
    double Red = 11.4;
    double White = 4.3;

    String[] subjectArray = {subject2,subject3,subject4,subject5};

    for (String subjects: subjectArray)
    {
        if (subjects.toUpperCase().contains("BLUE"));
        System.out.println(Blue+ "Blue ");
        arrlist.add(Blue);
        if (subjects.toUpperCase().contains("BLACK"));
        System.out.println(Black+" Black");
        arrlist.add(Black);
        if (subjects.toUpperCase().contains("WHITE"));
        System.out.println(White+" White");
        arrlist.add(White);
        if (subjects.toUpperCase().contains("RED"));
        System.out.println(Red+" Red");
        arrlist.add(Red);
    }
    System.out.println(sum(arrlist));
}

public static double sum(ArrayList<Double>arrlist)
{
  double result = 0;
  for (double number:arrlist)
  result += number;
  return result;
    }


   }

这满足了我的需要,但我想知道是否有更好或更直观的方法来做到这一点?我可以将 if 语句组合到单个对象 / class 然后调用 class 来搜索数组吗?使用 switch 语句会更好吗?我尝试使用正则表达式进行搜索,但 .contains 似乎也能正常工作。

只需使用包含您的关键字双关联的数组(或集合),并循环遍历该数组:

public class Keyword {
    private String value;
    private double points;

    ...
}

private Keyword[] keywords = new Keyword[] {
    new Keyword("BLUE", 1.6),
    new Keyword("BLACK", 10.1),
    ...
}

for (String subject : subjectArray) {
    for (Keyword keyword : keywords) {
        if (subject.toUpperCase().contains(keyword.getValue())) {
            System.out.println(keyword.getPoints() + " " + keyword.getValue());
            arrlist.add(keyword.getPoints());
        }
    }
}

我没有足够的声誉来发表评论,但这不是比将字符串转换为大写更有效吗?

org.apache.commons.lang3.StringUtils.containsIgnoreCase(String, String)

库的文档:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html