我有两个清单
Collection<String> listOne = new ArrayList<String>();
Collection<String> listTwo = new ArrayList<String>();
for(PermissionDataObject permissionDataObject : selectedPermissions)
listOne.add(permissionDataObject.getPermissionName());
for(String selectedPermissions : selectedList)
listTwo.add(selectedPermissions);
Collection<String> similarPermissions = new HashSet<String>(listOne);
Collection<String> differentPermissions = new HashSet<String>();
differentPermissions.addAll(listOne);
differentPermissions.addAll(listTwo);
similarPermissions.retainAll(listTwo);
differentPermissions.removeAll(similarPermissions);
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similarPermissions, differentPermissions);
输出是
One:[MENU_CREATION, ROLE_CREATION]
Two:[CREATE_BRANCH, CREATE_COUNTRY, MENU_CREATION, ROLE_CREATION]
Similar:[ROLE_CREATION, MENU_CREATION]
Different:[CREATE_BRANCH, CREATE_COUNTRY]
上面的代码完美运行我得到了不同的集合
但我想检查 listTwo 和 differentPermissions,如果不同并且 listTwo 等于 doSomething 如果不同并且 listTwo 不等于 doSomthing
我有下面的代码,当不同的有一个值时它的工作,如果不同的有更多的值,则循环被打破
for (Iterator<String> it = differentPermissions.iterator(); it.hasNext();){
String diffString = it.next();
String selectedString = selectedList.listIterator().next();
log.info("---diffString---" + diffString);
log.info("---selectedString---" + selectedString);
if(diffString == selectedString){
System.out.println("----permission added----" + diffString);
}else{
System.out.println("----permission deleted----" + diffString);
}
}
任何想法,对我来说都很棒......
谢谢普拉迪普
[编辑] 我的代码中的小改动请参见下面的完整代码
Collection<String> listOne = Arrays.asList("MENU_CREATION", "ROLE_CREATION");
Collection<String> listTwo = Arrays.asList("CREATE_BRANCH", "CREATE_COUNTRY", "MENU_CREATION", "ROLE_CREATION");
Collection<String> similar = new HashSet<String>(listOne);
Collection<String> different = new HashSet<String>();
different.addAll(listOne);
different.addAll(listTwo);
similar.retainAll(listTwo);
different.removeAll(similar);
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
for (Iterator<String> it = different.iterator(); it.hasNext();) {
String diffString = it.next();
String selectedString = listTwo.iterator().next();
if (diffString.equals(selectedString)) {
System.out.println("----permission added----" + diffString);
} else {
System.out.println("----permission deleted----" + diffString);
}
}