你好,我在比较两个数组列表时感到困惑,我的一个数组列表为:
private ArrayList<String> members = new ArrayList<>();
members.add("member123keyxyzmember123 number");
members.add("member456keyxyzmember456 number");
members.add("member789keyxyzmember789 number");
members.add("member2233keyxyzmember2233 number");
members.add("member1122keyxyzmember1122 number");
第二个arraylist是:
private ArrayList<String> syncMembers = new ArrayList<>();
syncMembers.add("member123keyxyz123statuskeyxyz123photokeyxyzmember123 number");
syncMembers.add("member456keyxyz456statuskeyxyz456photokeyxyzmember456 number");
问题是我正在比较两者,以便他们给我成员列表中的数字,而不是 syncMembers 列表!
这就是输出应该是:
member789 number
member2233 number
member1122 number
仅!
我一直在尝试的是:
for (int i = 0; i < members.size(); i++) {
String stringFromMembersList = members.get(i);
String[] memberParts = stringFromMembersList.split("keyxyz");
String memberNumber = memberParts[1];
//Log.e("hgax", "sync:::" + memberNumber);
for (int j = 0; j < syncMembers.size(); j++) {
String stringFromSyncList = syncMembers.get(j);
String[] syncParts = stringFromSyncList.split("keyxyz");
String n = syncParts[3];
if (memberNumber.equals(n)) {
//Log.e("hgax", "hee:::" + n);
break;
} else {
Log.e("hgax", "ssshee:::" + memberNumber);
}
}
}
我得到的输出是:
member456 number
member789 number
member789 number
member2233 number
member2233 number
member2233 number
member1122 number
member1122 number
member1122 number
member1122 number
我有点混淆发生在我身上的事情以及我做错了什么?有人可以告诉我在做什么大错的事先谢谢
答案 0 :(得分:0)
修改:更新了答案,以便在arrayList
ArrayList<String> membersList = new ArrayList<>();
ArrayList<String> syncMembersList = new ArrayList<>();
for (int i = 0; i < members.size(); i++) {
String s = members.get(i).substring(members.get(i).lastIndexOf("member"));
membersList.add(s);
}
for (int j = 0; j < syncMembers.size(); j++) {
String s = syncMembers.get(j).substring(syncMembers.get(j).lastIndexOf("member"));
syncMembersList.add(s);
}
for (int i = 0; i < membersList.size(); i++) {
if (!syncMembersList.contains(membersList.get(i))) {
System.out.println(membersList.get(i));
}
}
这将打印您需要的输出。
答案 1 :(得分:0)
尝试考虑一下您需要检查什么才能达到目标。为了确定members
中列表syncMembers
中的成员不存在,您必须检查该成员的syncMembers
列表的全部内容。由于列表不相同(如您的问题所述),因此您无法使用Collection.contains(Object o)
。
这应该达到你的目标:
// We need this initial check as if syncMembers is empty it'll display all members
// And why bother to do this if syncMembers is empty anyway!
if (!syncMembers.isEmpty()) {
for (String member : members) {
String memberNo = member.split("keyxyz")[1];
int i = 0;
boolean found = false;
while (!found && i < syncMembers.size()) {
// Iterate over syncMembers until a match if found
// or we have exhausted the list
found = syncMembers.get(i).split("keyxyz")[3].equals(memberNo);
i++;
}
if (!found) {
// Display only if not found
System.out.println(memberNo);
}
}
}