我想在java中从数组中分离出类似的值

时间:2014-06-23 06:10:09

标签: java arrays

请参阅下面的代码,请让我知道更正。 我写了我的预期结果..请帮帮我。

    try
{
    List<String> assocIds= new ArrayList<String>();

    List<String> actionids= new ArrayList<String>();
    assocIds.add("1");
    assocIds.add("2");
    assocIds.add("3");
    assocIds.add("5");

    actionids.add("2");
    actionids.add("3");
    actionids.add("7");
    actionids.add("4");
    actionids.add("6");


    List<String> matchFromFirstArray= new ArrayList<String>();
    List<String> notMatchFromFisrtArray= new ArrayList<String>();
    List<String> notMatchFromSecondArray= new ArrayList<String>();

    for(int j=0;j<assocIds.size();j++)
    {
        for(int i=0;i<actionids.size();i++)
        {
            if(assocIds.get(j).equalsIgnoreCase(actionids.get(i)))
            {
                matchFromFirstArray.add(assocIds.get(j));

            }else
            {
                notMatchFromFisrtArray.add(assocIds.get(j));
                notMatchFromSecondArray.add(actionids.get(i));
            }
        }
    }

    System.out.println("match from first array : "+matchFromFirstArray.toString());
    System.out.println("not match from fisrt array : "+notMatchFromFisrtArray.toString());
    System.out.println("unmatch form second array : "+notMatchFromSecondArray.toString());


}catch (Exception e) {
    System.out.println("Error :"+e);
}
}

My Expected Result:

从第一个阵列匹配:[2,3]

与fisrt数组不匹配:[1,5]

unmatch form second array:[7,4,6​​]

My OUTPUT:

从第一个阵列匹配:[2,3]

与fisrt数组不匹配:[1,1,1,1,1,2,2,2,3,3,3,3,5,5,5,5,5]

unmatch form second array:[2,3,7,4,6​​,3,7,4,6​​,2,7,4,6​​,2,3,7,4,6​​]

1 个答案:

答案 0 :(得分:1)

List<String> matchFromFirstArray= new ArrayList<String>();
List<String> notMatchFromFisrtArray= new ArrayList<String>();
List<String> notMatchFromSecondArray= new ArrayList<String>();

matchFromFirstArray.addAll(assocIds);
matchFromFirstArray.retainAll(actionids); // retains all matching elements


notMatchFromFisrtArray.addAll(assocIds);
notMatchFromFisrtArray.removeAll(matchFromFirstArray); // retains all not matching elements from first array



notMatchFromSecondArray.addAll(actionids);
notMatchFromSecondArray.removeAll(matchFromFirstArray); // retains all not matching elements from second array