检查arraylist上的字符串是否相同?

时间:2015-02-03 04:36:17

标签: java

CandidateList是一个由候选人姓名组成的列表。选票是一个字符串列表。我想检查选票列表上的第一个名字是否与candidateList上的任何名字相同。如果没有,那么我想检查选票上的下一个字符串,看看该字符串是否与candidateList上的任何名称相同。等等......

/**
     * @param candidateList a list of candidate names
     * @return the name of the first choice candidate for this Ballot from those
     * in candidateList
     */
    public String firstChoiceFrom(ArrayList<String> candidateList) {

        String firstChoice = "";
        String candidate = "";
        for (int can = 0; can < candidateList.size(); can++) {

            String bal = ballot.get(can); // gets next ballot
            candidate = candidateList.get(can); // gets next candidate
             while (!candidate.equals(bal))
             {

             }
            //checks to see whether the first name on the ballot
            if (candidate.equals(bal)) {        
                return candidate;
            } 

        }

3 个答案:

答案 0 :(得分:3)

如果要比较两个列表并仅保留常用列表。就像你在一篇评论中提到的那样

  

我想做的就是返回两个列表都有的字符串。

你可以在下面做:

list1.retainAll(list2); // This will keep all elements that matches list 2 and remove other
for(String word: list1)
{
System.out.println(word); //it will print all words in list 1
}

修改:回答您的评论。是的,你可以一个一个地做,但不推荐它,因为列表有函数retainAll

逐一比较就是这样:

for(String word : list1) //for each string in list 1
{
    if list2.contains(word);  // if list2 has the string
    {
      list3.add(word);  // add it in new list
    }
}

然后你可以打印如上所示的列表3

答案 1 :(得分:1)

如果找到匹配项,您想要做什么?

for(String s : list1){
if(list2.contains(s)){
// set a flag and break
}
}

这个块基本上迭代列表一检查String是否包含在列表2中。可以根据你想要实现的目标来改进代码。

根据要求进行编辑

List<String> list1 = new ArrayList<String>();

    list1.add("1");
    list1.add("2");
    list1.add("3");

    List<String> list2= new ArrayList<String>();
    list2.add("11");
    list2.add("12");
    list2.add("3");

    List<String> list3 = new ArrayList<String>(list2);
    list3.retainAll(list1);
    System.out.println(list3);
    //if you dont mind replacing your initial list, then you can use
    list1.retainAll(list2);
    System.out.println(list1);

答案 2 :(得分:0)

你想要解决这个问题的方式是你如何形容它:对于你投票箱中的每一张选票,如果选票与候选人的名字相符,那么我们想要返回它。

如果我们找不到任何内容,请返回null。现实中,我们无能为力。请注意,这并不包括重复项(即投票箱中有两个具有相同名称的候选人),尽管可以进行简单的修改以允许它覆盖该案例。

for(String ballot : ballotBox) {
    if (candidateList.contains(ballot)) {
        return ballot;
    }
}
return null;
相关问题