gpt4 book ai didi

java - 我想在java中从数组中分离相似的值

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

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

    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);
}
}

我的预期结果:

第一个数组的匹配:[2, 3]

与第一个数组不匹配:[1, 5]

与第二个数组不匹配:[7, 4, 6]

我的输出:

第一个数组的匹配:[2, 3]

与第一个数组不匹配:[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 5, 5, 5, 5, 5]

与第二个数组不匹配:[2, 3, 7, 4, 6, 3, 7, 4, 6, 2, 7, 4, 6, 2, 3, 7, 4, 6]

最佳答案

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

关于java - 我想在java中从数组中分离相似的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359399/

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